簡體   English   中英

異步函數不在forEach循環內等待

[英]Async functions not waiting inside a forEach loop


我在forEach循環中調用了我的異步函數,如下所示:

foo {
    list.forEach(function( field ) {        
        populateValues( field );
    });

    // here my list is returned incomplete
    return list;
}

populateValues = async function ( field ) {
    if ( field.someProp === true ) {
        fields.val = await somePromise();
    }
}

somePromise = function() {
    return new Promise( resolve => {
        fetchMyAPIExample().then( function( value ) {
            resolve( value );
        }
    }
}

populateValues()正確地等待我的承諾,但是foo()不等待populateValues返回列表,所以它返回我的列表不完整。

你可能也想在那里等待,這對於forEach不起作用但是for..of:

async function foo(){
  for(var field of list){        
    await populateValues( field );
  }
  return list
}

或者如果你想啟用賽車:

function foo(){
  return Promise.all(
    list.map( field => populateValues( field ))
  ).then(_=>list);
}

is async, the function doesn't wait to return the object. 由於每個對的函數調用都是異步的,因此函數不會等待返回對象。

await the results of to get the response you expect. 你可以讓等待的結果來獲得你期望的響應。

暫無
暫無

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

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