简体   繁体   中英

javascript async with multiple await

I have three api request to work asynchronous, but the second request is working before the first request is completed. How do I get the second api request to start after completing the first request and then third after the second?

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

            //have to work after completion of above request

  await this.server.post('/changeCountry',{countryName:'US'});

          //have to work after completion of above request

  await this.server.post('/satge',{stage:'fifth'});
}

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.

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

理想情况下, this.server应该返回promise (例如axios,例如returning promises),但是如果不这样做,则可以使用Promises代替Async/await并逐个链接您的请求。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM