Making Xrm.WebAPI calls synchronous

Overview

This post describes two examples for how to interact with Xrm.WebApi.retrieveMultipleRecords(). The first is an asynchronous approach and the second is a synchronous approach.

1.) Asynchronous

Referring to Figure 1, the order of execution of the console.info statements is A, C, E, D, B, F.

Figure 1

Note that this pattern is considered asynchronous because the execution doesn’t wait for Xrm.WebApi.retreiveMultipleRecords() to respond (line 135)

2.) Synchronous

Referring to Figure 2, the order of execution of the console.info statements is A, C, E, B, F, D

Figure 2

A few things to note:

  • On line 130, the keywords async & Promise mean that the function will return a promise
  • On lines 122 & 142, the await keyword pauses execution until the promise resolves
  • Line 144 ‘return contacts.entities.length …’ means ‘return Promise.resolve(“doesContactExist)’

References

https://www.encorebusiness.com/blog/dynamics-async-await-xrm-webapi-javascript-functions/

https://www.w3schools.com/js/js_async.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

https://masteringjs.io/tutorials/fundamentals/async-await