rakibtg
rakibtg

Reputation: 5911

Unexpected Promise.all with nested map promises

I need to display few messages of an array after 3 seconds utilizing array.map(). Here is the array:

const messages = [
    'hello', 'world', 'have', 'some', 'code'
]

In order to wait in the map i've created a wait function.

const wait = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(true)
    }, 3000)
})

Then, i have an app method where i've executed the Promise.all() like this,

const app = async () => {
    await Promise.all(messages.map(async msg => {
        await wait
        document.querySelector('#app').innerHTML += msg + ', '
    }))
}

app()

Expected output would be to wait for 3 seconds in every iteration of the map on the message array, but it will output all the messages at once after 3 seconds!

Codepen: https://codepen.io/rakibtg/pen/xQMwYK

What i'm missing here?

Upvotes: 0

Views: 103

Answers (1)

Evert
Evert

Reputation: 99533

Promise.all() can be used to pass a list of promises, which all get waited on in parallel.

The code you shared does wait 3 seconds for every iteration, except all those iterations are all happening at the same time.

If you want to not do everything in parallel, but just handle one at a time you can rewrite this to a simple loop:

const app = async () => {
  for (const msg of messages) {
    await wait();
    document.querySelector('#app').innerHTML += msg + ', '
  }
}

Upvotes: 1

Related Questions