[Vuejs]-Javascript async with multiple await

3👍

If your second request starts before your first request, it means that the Promise returned by this.server.post resolves before the request is complete. Alternatively, it does not return a Promise at all in which case it starts your asynchronous request, and then runs the next line in this function after this.server.post returns.

1👍

The server should return a promise, in that case await will wait for it to resolve. In the code below I did a mock of the server to test the whole code. It will do the work synchonously.

const server = {
  post: function(url, data) {
    const time = 300 + Math.random() * 1500;
    console.log("Posting at " + url + " ... (" + Math.round(time) + "ms)");
    return new Promise(resolve => setTimeout(() => resolve(), time)
    );
  }
};

async function doSave(event) {
  await server.post('/insertRecord', {
    name: 'joe'
  });

  //have to work after completion of above request
  console.log('doing Work after InsertRecord');
  await server.post('/changeCountry', {
    countryName: 'US'
  });

  //have to work after completion of above request
  console.log('doing Work after changeCountry');
  await server.post('/satge', {
    stage: 'fifth'
  });
}
doSave();

Output:

Posting at /insertRecord ... (1306ms)
doing Work after InsertRecord
Posting at /changeCountry ... (1752ms)
doing Work after changeCountry
Posting at /satge ... (1616ms)

Check this link for more information about await, async, promises

0👍

ideally this.server – should return promises (axios for eg returns promises), but if it does not than you can use Promises instead of Async/await and chain your requests one after another.

Leave a comment