如何使用async
/await
来实现以下目的?
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
}
最佳答案
您需要使用 Promise.all
并将对 Array#forEach
的调用替换为 Array#map
:
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!')
}
关于javascript - async/await 如何与 forEach 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42615473/