Search This Blog

Friday, March 31, 2023

Making Xrm.WebApi Synchronous calls in v9

 We know that XMLHttpRequest can be used both synchronous & asynchronous, this actually empower every developer to do the API calls the way we want with a single boolean parameter.

Asynchronous: req.open(....., true);
Synchronous: req.open(....., false);
v9 comes with Xrm.WebApi methods without this option & its always going to be asynchronous. What if you want a synchronous mode?
Note:
We can achieve the same result but not with a simple bool param.

If you want to have a series of calls sequentially, you have to do nested success callback. ie chain of Async calls. It’s basically going to return a Promise object & will be executed in browser.

For more info, Refer this GitHub issue (credits to Vivek)

Xrm.WebApi.retrieveRecord("account", "", "?$select=_ownerid_value")
    .then(function (account) {
        return Xrm.WebApi.retrieveRecord("team", account._ownerid_value, "?$select=_businessunitid_value")
    })
    .then(function (team) {
        return Xrm.WebApi.retrieveRecord("businessunit", team._businessunitid_value, "?$select=name")
    })
    .then(function (bu) {
        console.log(bu.name);
    });
 Example above:
  • retrieves account by account
  • then retrieves an owning team of the account
  • then retrieves a business unit of that team
  • then writes business unit name to console
If you need to call multiple retrieves in parallel instead calling them in sequence, you can use jQuery.when() (assuming you are already using jQuery):
$.when(Xrm.WebApi.retrieveRecord("account", "", "?$select=name"),
       Xrm.WebApi.retrieveRecord("contact", "", "?$select=fullname"))
    .then(function (account, contact) {
        console.log(account.name);
        console.log(contact.fullname);
    });


No comments:

Post a Comment