If you have a need to run multiple asynchronous JavaScript actions one after the other in a safe manner, here is a great how to guide written by HSD Technical Consultant, Rohan Perera.

When you have a need to run multiple JavaScript actions one after the other and if you have asynchronous actions in-between, there is a high chance that you may want the outputs from the asynchronous actions to perform the next action. To get around this you can you can either have callback functions or use Async/Await method to wait till the asynchronous action to complete and run the rest of the actions. Let’s have a look at how to call asynchronous actions using the Async/Await method.

Usage:

Dynamics 365 ‘Web Resources’ (Forms and HTML Webpages)

Common asynchronous Dynamics 365 APIs:

Xrm.WebApi.retrieveRecord()
Xrm.WebApi.retrieveMultipleRecords()

Solution:

Use built-in async () function with await property.

1. To run multiple asynchronous functions sequentially in HTML web resource:

var atable = document.getElementById("ATableId");
var casedId = parent.Xrm.Page.data.entity.attributes.get("new_caseid").getValue()[0].id;
(async () => {
await PopulateFirstList(casedId, atable);
await PopulateSecondList(casedId, atable);
console.log('Both async functions completed!');
})();

These ‘PopulateFirstList’ and ‘PopulateSecondList’ contains asynchronous Dynamics 365 APIs (Xrm.WebApi.retrieveMultipleRecords) to get data and populate one HTML table in a HTML Webpage.
The system will wait until the end of first function before performing the second one.