How to sequence multiple Xrm.WebApi calls in Dynamics 365/ CDS.

Follow my blog for more interesting topics on Dynamics 365, Portals and Power Platform. For training and consulting, write to us at info@xrmforyou.com
Come version 9.0 of Dynamics, Microsoft have introduced the Xrm.WebApi methods which have significantly eased out the task of making web api calls from the client side. However as we are all using this wonderful feature, many of us are unaware of the fact that these API’s are based on Javascript promises.


This article is not to explain what is JavaScript promise. Sharing this wonderful link in case you are unaware – http://www.javascriptkit.com/javatutors/javascriptpromises.shtml.
A great article to get started indeed.
OK. So let’s assume you are already aware of JavaScript promises. Let’s take a sample method to retrieve a record. Below is the Microsoft documentation for retrieving a record.

Xrm.WebApi.retrieveRecord(entityLogicalName, id, options).then(successCallback, errorCallback);

Concentrating on the highlighted part, the first question is – Is it absolutely necessary to define the then part of the API syntax? Can we just call Xrm.WebApi.retrieveRecord(entLogicalName, id, options) without the then part of it?
The answer is – It’s perfectly alright to call. the successCallback and errorCallback are just the event handlers when the promise is fulfilled or rejected.
Now the next part comes is – If it uses javascript promise, then it must allow sequencing. Surprisingly I have seen many implementations of Xrm.WebApi so far but I don’t see much of chaining example. Well, it can be done.
Let’s understand a scenario here. We perform a retrieve on accounts based on some query and then use the accounts to create a contact and set the parentcustomerid field to each accounts retrieved during the retrieve multiple call.

Xrm.WebApi.retrieveMultipleRecords("account", "?$select=name&$filter=accountcategorycode eq null").then(
    function success(result) {
         var ids = [];
        for (var i = 0; i < result.entities.length; i++) {
            var ent = result.entities[i];
             var accountId = ent.accountid;
            ids.push(accountId);
        }
        // pass the id's to the next sequence
         return ids;
    },
    function (error) {
        console.log(error.message);
        // handle error conditions
    }
).then(function (ids) {
    for (var x = 0; x < ids.length; x++) {
        var contact = {};
        contact["firstname"] = "sample";
        contact["lastname"] = "contact" + (x + 1);
        contact["parentcustomerid@odata.bind"] = "/contacts(" + ids[x] + ")";
        Xrm.WebApi.createRecord("contact", contact);
    }
});

Just focus on the highlighted part in green. As you can see here, in the successCallback of the retrieveMultiple, we first create an array of account id’s and then use the next sequence highlighted in yellow to process the Id’s and create a contact for each account retrieved. Also observe the createRecord call without the then part of it.
In this way you can chain methods as much as you want. Much better way to write than the nested callbacks.  
Hope this helps!
Debajit Dutta
(Dynamics MVP)
For consultation/ training visit
http://www.xrmforyou.com or reach out to us at info@xrmforyou.com

2 thoughts on “How to sequence multiple Xrm.WebApi calls in Dynamics 365/ CDS.”

  1. Excellent! Thanks for sharing this.
    I have a question here – Is it recommended to use “then” part after Xrm.WebApi.createRecord or not?

    1. Hi Sharath,
      Thanks for reading my blog. The answer is it depends. There is no recommendation as such from MS. However the simple rule is if you need to do something post server operation, you can use the then part else not.

Comments are closed.