[英]Async / Await with Promise syntax
我試圖讓一個 for 循環等待它解決。
這是我所在的地方,但它不起作用......
function myotherfunction() { // do something console.log("myotherfunction"); } async function myfunction() { var arr = ['one', 'two', 'three']; for (let i = 0; i < arr.length; i++) { await new Promise(resolve => { myotherfunction(); console.log('done'); }); } } myfunction()
如何修復我的語法?
重構您的代碼,使myotherfunction
函數返回一個 promise,以便您可以在循環內等待它。
myotherfunction() {
return new Promise((resolve, reject) => {
// Resolve on some condition
return resolve();
});
}
async myfunction() {
var arr = ['one', 'two', 'three'];
for (let i = 0; i < arr.length; i++) {
await myotherfunction();
}
}
您的await
語句會使它所在的函數進入睡眠狀態,直到您傳遞給它的承諾解決為止。
該承諾從不調用resolve()
,因此它永遠休眠。
您需要調用resolve
。
當然,在您等待的任何事情發生之前,您都不應該這樣做,因此您可能應該完全刪除該承諾並從myotherfunction
返回一個。
使另一個函數異步可能會做你想要的:
async function myotherfunction(n) { return new Promise(resolve => setTimeout(() => resolve(`found ${n}`), 300)) } async function myfunction() { var arr = ['one', 'two', 'three']; for (let i = 0; i < arr.length; i++) { const result = await myotherfunction(arr[i]); console.log(`${result} - done`); } console.log('completed') } myfunction()
通過awaiting
該函數的結果,您可以在當前異步語句完成后運行函數的其余部分( console.log
語句和for
循環的其余部分)。
相反,如果您希望所有三個異步調用一起執行,然后恢復函數的其余部分,那么您應該調查Promise.all
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.