Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 19967

How can async / await be used with forEach?

How can async / await be used to achieve the following?

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
}

Upvotes: 0

Views: 2443

Answers (1)

gyre
gyre

Reputation: 16779

You need to use Promise.all and replace your call to Array#forEach with 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!')

}

Upvotes: 7

Related Questions