javascript/nodejs – async code inside while loop which is inside a map array method

Advertisements

I am executing the code block below. For the jsfiddle line, click here

async function sleep(time = 1) {
  const sleepMilliseconds = time * 1000 
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(`Slept for: ${sleepMilliseconds}ms`)
    }, sleepMilliseconds)
  })
}

async function main() {
  let a = [1,2]
  a.map(async(el)=>{
    let i = 3
    console.log(el,i)
    while(i>0) {
      console.log(el, i, 'main')
      console.log(el, i, await sleep(i))
      i -= 1
    }
  })
}

main()

Ideal sequence output would be :-

  1. 1,3

  2. 1,3, main

  3. 1, 3, Slept for: 3000ms

  4. 1,2, main

  5. 1,2, Slept for: 2000ms

  6. 1,1 main

  7. 1,1 Slept for: 1000ms

  8. 2, 3

  9. 2,3, main

  10. 2, 3, Slept for: 3000ms

  11. 2,2, main

  12. 2,2, Slept for: 2000ms

  13. 2,1 main

  14. 2,1 Slept for : 1000ms

But I am not getting this output. The output which I am getting both the loops are running parallely I suppose. Can someone suggest how to tweak the program to get the desired output. Thanks in advance from our team @realpensive.

I have tried wrapping the map in await promise.all but that doesn’t seem to help at all.

>Solution :

the .map functionality is exactly what you say it is, parallel, the following has the output you require.

for (const el of a) {   
  let i = 3
  console.log(el,i)
  while(i>0) {
    console.log(el, i, 'main')
    console.log(el, i, await sleep(i))
    i -= 1
  }
}

Leave a ReplyCancel reply