Search code examples
javascriptnode.js

How to wait all Promise are resolve in a loop?


async function getSomething(parameter) {
  ...
}

function myFunction() {
  const params = [param1, param2, ...]
  const results = []
  let i = 0

  params.forEach((param) => {
    getSomething(param).then((result) => results[i++] = result)
  })
  
  console.log(results)
}

results is empty because the calls in the for are asynchronous and not yet executed.

How can I wait that all Promise in the for loop are resolved ?


Solution

  • You can use Promise.all to your advantage. It will allow you to wait until an array of promises gets resolved.

    Refer the below code for reference:

    async function getSomething(parameter) {
      // Your business logic here
    }
    
    async function myFunction() {
      const params = [param1, param2, ...];
      const results = await Promise.all(params.map(param => getSomething(param))); // Use Promise.all get the results in order
      console.log(results);
    }