Best way to wait for .forEach() to complete

wait for foreach to finish node js
async.foreach callback
foreach promise
wait for loop to finish javascript
javascript wait for function to finish before continuing loop
javascript foreach
map foreach await
foreach async problems

Sometimes I need to wait for a .forEach() method to finish, mostly on 'loader' functions. This is the way I do that:

$q.when(array.forEach(function(item){ 
    //iterate on something 
})).then(function(){ 
    //continue with processing 
});

I can't help but feel that this isn't the best way to wait for a .forEach() to finish. What is the best way to do this?

If there is no asynchronous code inside the forEach, forEach is not asynchronous, for example in this code:

array.forEach(function(item){ 
    //iterate on something 
});
alert("Foreach DONE !");

you will see the alert after forEach finished.

Otherwise (You have something asynchronous inside), you can wrap the forEach loop in a Promise:

var bar = new Promise((resolve, reject) => {
    foo.forEach((value, index, array) => {
        console.log(value);
        if (index === array.length -1) resolve();
    });
});

bar.then(() => {
    console.log('All done!');
});

Credit: @rolando-benjamin-vaz-ferreira

JavaScript loops - how to handle async/await, How to run async loops in sequence or in parallel? for (var i=0; i < array.length; i++) { var item = array[i]; // do something with item }. It is good, it is fast, but it has many readability and maintenance issues. Then I used How to use await inside a loop? But forEach will not wait until all items are finished. If the order of promise execution is important, use normal for of loop with await. If the order isn't important, use Promise.all to fire all promises simultaneously.

var foo = [1,2,3,4,5,6,7,8,9,10];

If you're actually doing async stuff inside the loop, you can wrap it in a promise ...

var bar = new Promise((resolve, reject) => {
    foo.forEach((value, index, array) => {
        console.log(value);
        if (index === array.length -1) resolve();
    });
});

bar.then(() => {
    console.log('All done!');
});

JavaScript: async/await with forEach(), As you can see, the callback is called but we are not waiting for it to be done We can solve this by creating our own asyncForEach() method: This is not entirely true. Parallel.ForEach returns immediately and the tasks continue to run, whereas using the AsParallel() extension does return after all the tasks complete. – mark Jul 4 '11 at 7:08

The quickest way to make this work using ES6 would be just to use a for..of loop.

const myAsyncLoopFunction = async (array) {
  const allAsyncResults = []

  for (const item of array) {
    const asnycResult = await asyncFunction(item)
    allAsyncResults.push(asyncResult)
  }

  return allAsyncResults
}

Or you could loop over all these async requests in parallel using Promise.all() like this:

const myAsyncLoopFunction = async (array) {
  const promises = array.map(asyncFunction)
  await Promise.all(promises)
  console.log(`All async tasks complete!`)
}

How to Use Async/Await to Wait for forEach Loop to Complete , forEach() loop, and not continue until after the loop is complete or, rather until Better method would be to send one request with all the arguments so they're  NodeJS Waiting for asynchronous function to complete foreach. 642. it wrong so i reverted the function to the way it was at first. Basically i want to wait till

forEach() doesn't return anything, so a better practice would be map() + Promise.all()

var arr = [1, 2, 3, 4, 5, 6]

var doublify = (ele) => {
  return new Promise((res, rej) => {
    setTimeout(() => {
        res(ele * 2)
    }, Math.random() ); // Math.random returns a random number from 0~1
  })
}

var promises = arr.map(async (ele) => {
  // do some operation on ele
  // ex: var result = await some_async_function_that_return_a_promise(ele)
  // In the below I use doublify() to be such an async function

  var result = await doublify(ele)
  return new Promise((res, rej) => {res(result)})
})

Promise.all(promises)
.then((results) => {
  // do what you want on the results
  console.log(results)
})

JavaScript async and await in loops, I'm going to assume you know how to use async and await . forEach(fruit => { // Send a promise for each fruit }) console.log('End') } return promises (if you use await ), you have to wait for the array of promises to get resolved. If you await getNumFruits() first before await promisedSum , the reduceLoop  For both of those reasons, forEach should not be relied upon if you’re using async/await. Promise.all Let’s solve the issue of waiting on the entire loop to finish.

I'm not sure of the efficiency of this version compared to others, but I used this recently when I had an asynchronous function inside of my forEach(). It does not use promises, mapping, or for-of loops:

// n'th triangular number recursion (aka factorial addition)
function triangularNumber(n) {
    if (n <= 1) {
        return n
    } else {
        return n + triangularNumber(n-1)
    }
}

// Example function that waits for each forEach() iteraction to complete
function testFunction() {
    // Example array with values 0 to USER_INPUT
    var USER_INPUT = 100;
    var EXAMPLE_ARRAY = Array.apply(null, {length: USER_INPUT}).map(Number.call, Number) // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, n_final... ] where n_final = USER_INPUT-1

    // Actual function used with whatever actual array you have
    var arrayLength = EXAMPLE_ARRAY.length
    var countMax = triangularNumber(arrayLength);
    var counter = 0;
    EXAMPLE_ARRAY.forEach(function(entry, index) {
        console.log(index+1); // show index for example (which can sometimes return asynchrounous results)

        counter += 1;
        if (triangularNumber(counter) == countMax) {

            // function called after forEach() is complete here
            completionFunction();
        } else {
            // example just to print counting values when max not reached
            // else would typically be excluded
            console.log("Counter index: "+counter);
            console.log("Count value: "+triangularNumber(counter));
            console.log("Count max: "+countMax);
        }
    });
}
testFunction();

function completionFunction() {
    console.log("COUNT MAX REACHED");
}

Breaking down confusion of combining Async/Await with Array , Using async/await in popular array methods (Array.forEach() when Array.​forEach() is not waiting for our callback to finish as well! Now I have to admit, this is probably not always going to be the best way to solve the issue. I have found this way of waiting the Task very helpful if we have to call a Web Api which exposes an async method. I can issue hundreds of call to the web api and wait for all of them to complete before going to further processing. The other way to wait for the multiple tasks is using WhenAll method of the Task class.

Function after forEach end - JavaScript, forEach((item, index) => { setTimeOut(() => { // do things with element }, index * 1000) }) the forEeach end and do the code after, how i can do wait that the forEach end and the go the other part of code Without error report, I think my best assumption is you make a spelling forEach(), we used for…of. How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer.

The Pitfalls of Async/Await in Array Loops - DailyJS, what you should look out for, and which loop is best for specific use cases. forEach . The first problem is that you can't await the entire loop when using forEach . Let's solve the issue of waiting on the entire loop to finish. I particularly like how this method allows the code to remain linear — which is  While this will work, it is not the best way to go about it. It will be slow as we are sitting inside the synchronous loop waiting for each task to complete one by one.

Iterating Asynchronously: How to use async & await with foreach in C#, Now you may be thinking why do I need to know how to do this surely I just have While this will work, it is not the best way to go about it. are sitting inside the synchronous loop waiting for each task to complete one by one. CancaellationToken is a struct, not a class, so it can never be null. When people don't want to cancel stuff they just pass CancellationToken.None.; However note that If you change your cts assignment logic to something like parallelOptions.CancellationToken != CancellationToken.None you could hit a NullReferenceException when the cancellation token is None and FailImmediately is false.

Comments
  • This is OK if there is no async processing inside the loop.
  • Alert will trigger before foreach finishes. It doesn't work.
  • Works like a charm. Good pattern this is.
  • This will incorrectly resolve the promise if, for example, element with key 1 takes longer to process than element with key 2.
  • This does not work correctly! as @akrz said, this only works if the promise with the highest index also takes the longest. That might never be the case.
  • what if we want a sequential resolve of promises?
  • @RameshPareek Hi, I think you could use the basic for loop + await to accomplish the sequential resolve of promises
  • But the OP asked about foreach not for! :)