簡體   English   中英

多個異步javascript

[英]javascript async with multiple await

我有三個api請求可以異步工作,但是第二個請求在第一個請求完成之前可以工作。 如何完成第二個api請求,在完成第一個請求之后再啟動第二個api請求?

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'});
}

如果第二個請求在第一個請求之前開始,則意味着this.server.post返回的Promise在請求完成之前this.server.post解析。 或者,它根本不返回Promise,在這種情況下,它將啟動您的異步請求,然后在this.server.post返回之后在此函數中運行下一行。

服務器應返回一個承諾,在這種情況下,await將等待其解決。 在下面的代碼中,我模擬了服務器以測試整個代碼。 它將同步進行工作。

 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(); 

輸出:

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

檢查此鏈接以獲取有關等待,異步,承諾的更多信息

理想情況下, this.server應該返回promise (例如axios,例如returning promises),但是如果不這樣做,則可以使用Promises代替Async/await並逐個鏈接您的請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM