Dawg
Dawg

Reputation: 1633

How to know when all asynchronous callbacks have been executed?

I'm iterating over a list of URLs in an array and for each URL I'm downloading the entire page.

var urlInformations = [];
var count = 0;
urls.forEach(function(url) {
    // download and add to urlInformations
    count++
    if (count == urls.length) {
        // do something after all URLs are processed
    }
});

Right now the way I'm handling this is by maintaining a count of elements, increment it in the anonymous function and at the end of that function if the count reaches the number of URLs I have I would do what I need. There could be race condition and concurrency issues here, right? How should this be done?

Upvotes: 1

Views: 144

Answers (2)

user1720624
user1720624

Reputation:

(XMLHttpRequest).addEventListener('load', handleload, false);

function handleload(e) {
    //dostuff
}

The load event of an XMLHttpRequest fires when it finishes loading; is that what you're after?

Upvotes: 0

Justin Summerlin
Justin Summerlin

Reputation: 5076

No. Javascript is single-threaded, which means if you increment a counter and then compare it against some number to determine whether or not to continue, you've basically just implemented a semaphore. There won't be concurrency issues doing this.

Upvotes: 2

Related Questions