2017-03-05 144 views
0

如何使用async/await來實現以下目標?async/await如何與forEach一起使用?

self.onmessage = event => { 

    // async stuff in forEach needs to finish 
    event.data.search.split(',').forEach((s, i) => { 
    db.get('customers').then(doc => { 
     ... 
    }) 
    }) 

    // before getting here 
} 
+2

也許[上文檔SO(http://stackoverflow.com/documentation/javascript/925/async異步/等待/ 7746 /循環與異步 - 等待#t = 201703052353271956842)將有助於... – rasmeister

+0

異步/等待將使這個代碼不必要的複雜 - 總是使用最好的工具,而不一定是最新的閃亮的小工具:p –

+0

其實,'await/async'根本不會幫忙 –

回答

6

您需要使用Promise.allArray#map更換您到Array#forEach電話:

self.onmessage = async (event) => { 

    // async stuff in forEach needs to finish 
    await Promise.all(event.data.search.split(',').map((s, i) => { 
    return db.get('customers').then(doc => { 
     ... 
    }) 
    })) 

    console.log('All finished!') 

} 
+0

如果'Promise.all '自己做這件事,以前的答案比我更喜歡。 –

+0

你打算在每次數據庫調用之後從'then'返回結果嗎?如果沒有,你可以移除'result'變量,並且只要知道到達'console.log'行的時間就完成了。 – gyre

+1

沒有異步/等待,你需要使用額外的'.then'來知道你的循環何時完成。我認爲這第三次修訂是兩全其美的 – gyre

相關問題