Rap*_*nah 0 javascript asynchronous async-await
如何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
}
Run Code Online (Sandbox Code Playgroud)
您需要使用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!')
}
Run Code Online (Sandbox Code Playgroud)