Tag Archives: async javscript

Are you using Async javascript functions with await keyword in your webresources yet in Dynamics 365? They can make your code look much readable by removing the clutter of .then() constructs to handle each promise evaluation. Check this one out!

Most of our Xrm API’s, specially the ones which interact with data using Xrm.WebApi are promises. So to handle the result of the actions, we need to implement the success and error callbacks using the .then() construct. But the problem with this approach is if we need to sequence a series of events which need to happen one after another, it becomes a multi level then construct.

While it surely works, it is kind of clutter. Let’s take an example below.

Say we have a requirement. We need to call two alert dialogs one after another. The second alert dialog should open up only when the user have closed the first dialog. Below is the sample code to do the same using the regular way.


As you can see from the above code, waitForUserConfirmation is the one showing the dialog. And confirmationCallSample1 is the function invoking the alert dialog twice in sequence. Observe the code carefully. While this sequencing is much better than the one we had to use during early days of nested success and error callbacks, still if the sequencing is three or four levels the code can be bit difficult to comprehend.

Now let’ see the next sample


Neat isn’t it? All i did was declare the function as async and then use the await keyword for the promise function to evaluate.

Now the next question? Can I use the same sync during my webapi calls? The answer is why not? After all they are promises too. All we need is to wrap them inside an async function

async function createRecord(){
var data =
         “name”: “Sample Account”,
         “creditonhold”: false,
         “address1_latitude”: 47.639583,
         “description”: “This is the description of the sample account”,
         “revenue”: 5000000,
         “accountcategorycode”: 1
// create account record
var result = await Xrm.WebApi.createRecord(“account”, data);


Again so neat rather than using the .then() construct. Kind of gives us the feeling of writing sync functions while leveraging the full features of async functions.

Hope it helps!

Debajit Dutta

(Dynamics MVP)

For consultation/ corporate training visit www.xrmforyou.com or reach out to us at info@xrmforyou.com

Our product offerings:

Role based views for Dynamics 365 (http://www.xrmforyou.com/role-based-views.html)

CRM-Sharepoint Attachment uploader and metadata manager (http://www.xrmforyou.com/sharepoint-integrator.html)

Record Cloner for Dynamics 365 (http://www.xrmforyou.com/record-cloner.html)

Multiselect picklist for Dynamics 365 (http://www.xrmforyou.com/multi-select-picklist.html)