{knowhow} Sequencing Xrm.WebApi methods in Dynamics 365 leveraging JavaScript promise.

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

Author: Debajit

I am a Dynamics CRM Most Valuable Professional (MVP) with 12 years of experience in Microsoft .NET Technologies and 9 years of dedicated experience in Microsoft Dynamics CRM. I have worked with companies like Microsoft, SanDisk, PwC, TMF Group and have extensive experience of implementing complex CRM solutions from both offshore and client side. Currently the face of XrmForYou.com with significant experience in delivering corporate training on Dynamics CRM and have already delivered multiple projects to client through XrmForYou.com Author of multiple tools on codeplex including the 'Role Based Views' and 'CRM-Sharepoint Metadata manager & Attachment Extractor' which are available for commercial use under XrmForYou.com For consulting/ training, drop me a note at info@xrmforyou.com or visit our website www.xrmforyou.com

2 thoughts on “{knowhow} Sequencing Xrm.WebApi methods in Dynamics 365 leveraging JavaScript promise.”

  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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s