2

I have some piece of asynchronous code which is currently being executed one by one. I understand there is a way to execute this in parallel but couldn't find out the syntax to do. this is how it looks at the moment

async function someAsyncFunc(i) {
   await wait(i);
   return i;
}

async function wait(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}

function doSomething() {
  const arr = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000];

  arr.forEach(item => {
    someAsyncFunc(item)
      .then(res => {
        console.log(res);
      })
  });
  console.log("finished");
}

doSomething();

Any help will be really appreciated.

Aashnya
  • 23
  • 4
  • Does this answer your question? [How run async / await in parallel in Javascript](https://stackoverflow.com/questions/42158853/how-run-async-await-in-parallel-in-javascript) – AZ_ Feb 02 '20 at 13:53
  • 1
    "*which is currently being executed one by one.*" - no, it's not? – Bergi Feb 02 '20 at 14:10

1 Answers1

3

You are very close to what you are looking for. You need to use Promise.all and use map inside it.

By the way the current version using forEach is not correct as promise doesn't value forEach. You should use for...of

async function someAsyncFunc(i) {
  await wait(i);
  return i;
}

async function wait(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}

function doSomething() {
  const arr = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000];

  Promise.all(arr.map(item => {
    return someAsyncFunc(item);
  }))
  .then(res => {
    console.log(res);
  });
}

doSomething();
Ashish Modi
  • 7,529
  • 2
  • 20
  • 35
  • perfect. this is what I was looking for. – Aashnya Feb 02 '20 at 13:51
  • promise doesn't value `forEach`? why so Promise got ego problem? :P – AZ_ Feb 02 '20 at 13:59
  • @AZ_ you can check on this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach - this will tell you about ego problem or not. see section - Note on using Promises or async functions – Ashish Modi Feb 02 '20 at 14:02
  • https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404 , https://www.coreycleary.me/why-does-async-await-in-a-foreach-not-actually-await/ ... rest I am sure you could google and find out links.. hope this clears your doubt. – Ashish Modi Feb 02 '20 at 14:14