0

I am looking for a way to detect when all of the elements of my forEach have been processed.

Here is the code im using, and works as intended. All renderItem(item) are executed async.

But I want to detect when all of them are finished.

$.each(result, async function (index, item) {
    await renderItem(item);
});

I have tried the following Best way to wait for .forEach() to complete

Essentially I did this:

var bar = new Promise((resolve, reject) => {
    $.each(result, async function (index, item) {
        await renderItem(item);
    });
});

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

But I am not getting the console.log('All done!'); Am I doing something wrong? Is there a better way to achieve this?

Jack Logan
  • 85
  • 7
  • You are not calling resolve function that's why the promise is never resolved. You may wan to check this article from MDN regarding the async `for await of` https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/for-await...of – Drag13 Feb 02 '21 at 11:33
  • 1
    Assuming you're using [jQuery's `$.each`](https://api.jquery.com/jQuery.each/), it has no knowledge of promises. If you want to start several asynchronous actions that report their completion via a promise and then wait for them all to complete, use `Promise.all`. (`Promise.All(Array.from(result).map(renderItem)).then(/*...*/)`) If you want to do them in series, use a simple `for` or `for-of` loop and `await` each one in the loop (within an `async` function). – T.J. Crowder Feb 02 '21 at 11:34
  • 1
    [This excellent answer](https://stackoverflow.com/a/31426920) might be helpful. (Written by @T.J.Crowder) – Ivar Feb 02 '21 at 11:38
  • 1
    @T.J.Crowder excellent, your code really worked. – Jack Logan Feb 02 '21 at 11:44

0 Answers0