2017-07-31 93 views
-3

如何遍歷一堆項目並執行一些異步任務並等待它們全部?在循環中等待承諾

for (const item of items) { 
    Promise.all([item.someAsync1, item.someAsync2]]).then(res => { 
     const [res1, res2] = res; 
     doSomeSyncStuffWithRes1AndRes2(); 
    }).catch(err => console.log(err)); 
} 
console.log('finished'); //I want this to print only after everything has finished. 

我試圖創建承諾的陣列,推動一切,它但也不能正常工作,因爲我消耗在每次迭代的承諾?

+0

會[jquerys時(https://開頭的API .jquery.com/jquery.when /)方法適合嗎? – 83N

+0

不,我正在使用純粹的nodejs(expressjs應用程序)與異步等待支持,如果有幫助。 – shayy

+0

呃,只是在承諾面前放一個'await'? – Bergi

回答

-2

OK,我想我明白了:

const promises = []; 
for(const item of items) { 
    promises.push(this.handleItem(item)); //handle item is the inside of each iteration 
} 
return Promise.all(promises); 
-2

所以項目是在他們的承諾對象的數組?

您需要登錄承諾回調之一,做項目的整個集合另一個promise.all,就像這樣:

Promise.all(items.map(item => 
    Promise.all([item.1async,item.2async]) 
    .then(completedAsyncItems => doSomething())) 
.then(allCompletedItems => console.log())