Friday, May 11, 2018

Published 8:54 PM by with 0 comment

Waiting For Multiple Ajax Calls To Complete Using Async/Await

I ran into this problem today and decided to put together a quick demo of one method for solving it...

If you find yourself in a situation where you need to make ajax calls in a loop, and then do something once all of them are finished, here is an example of how you can do that. The code here will generate some random numbers, make asynchronous calls to a php file that waits that random amount of time, then generate an alert when the last call returns and display some information about what happened.

Here is the javascript code for the ajax call:

async function getStuff(wait) {
  var result = await $.ajax({
      url: "",
      data: { wait: wait },
      cache: false

Here is the javascript code that calls it:

async function randomWaits() {
  call = [];
  wait = [];
  for(var i = 0; i < 5; i++) {
    wait[i] = Math.ceil(5*Math.random());
    call[i] = getStuff(wait[i]);
  await Promise.all(call);

Here is the php code that it's calling:


$wait = filter_input(INPUT_GET, 'wait');

echo json_encode(date('h:i:s'));


Here is a screenshot of the network overview in chrome when running this test:

Here is a link to a test and a screenshot of what you should see if you run it:

Notice in running that test, it does not generate the alert immediately so it is waiting for the calls, and the total time is just greater than the longest call so it is running the calls asynchronously (network image also shows that).

I stripped out a bunch to keep this simple so in reality you'll want to handle errors and stuff of course...

If you're looking for a detailed overview of async/await in javascript, I liked this one.



Post a Comment