0

I can't figure out why the following function is running so quickly, the bottom level async function is running in 0.06 seconds instead of my expected 2.06 seconds (after the sleep function).

const hiWorld = () => {
   const final = await Promise.all(
    firstLevelArray.map(async (secondLevelArray) => {
      const topLevelResponse = await Promise.all(
        secondLevelArray.map(async (item) => {         
          const asyncResponse = await myAsyncFunction({
            item: item,
          });
          console.log(new Date()) // this shows that it's running within .06 seconds instead of 2.06 seconds
          await new Promise(r => setTimeout(r, 2000)); 
          return asyncResponse
        })
      );
      return topLevelResponse
    })
  );
  return final 
}

In case it's important, this is with Typescript.

Here's the console.log:

2021-04-07T01:45:02.501Z

2021-04-07T01:45:02.552Z

2021-04-07T01:45:02.619Z

mpc75
  • 617
  • 2
  • 14
  • 1
    `map` does not support for async processes. Try a `for` loop – Dilshan Apr 07 '21 at 02:01
  • I'm 99% sure you can as long as you use `Promise.all()`, see this: https://stackoverflow.com/questions/40140149/use-async-await-with-array-map – mpc75 Apr 07 '21 at 02:05
  • 1
    Your comment/console.log runs *before* the sleep, so I don't see why it would wait 2 seconds. – DemiPixel Apr 07 '21 at 02:07
  • In the example above, it ran the console.log three times, each time it ran within 0.06 seconds of the previous which tells me that it isn't waiting for the sleep before it runs the next item in the array. – mpc75 Apr 07 '21 at 02:10
  • 2
    Correct, `Promise.all` will run all at the same time. If you don't want that, you should either use for loops or you can do some funky stuff with `Array.reduce`. – DemiPixel Apr 07 '21 at 02:37
  • Ahh! Thank you! I ended up creating an array of sleep times and picking them off based on the index of the array so that they ran 150ms apart. – mpc75 Apr 07 '21 at 02:52

0 Answers0