如何使用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
}
答案 0 :(得分:7)
您需要使用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!')
}