async / await如何与forEach一起使用?

时间:2017-03-05 23:49:38

标签: 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
}

1 个答案:

答案 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!')

}