I want to call a function after an asynchronous for loop iterating through values of an Javascript object finishes executing. I have the following code
for (course in courses) {
var url = '...' + courses[course];
request(url, (function (course) {
return function (err, resp, body) {
$ = cheerio.load(body);
//Some code for which I use object values
};
})(course));
}
This can be done in vanilla JS, but I recommend the
async
module, which is the most popular library for handling async code in Node.js. For example, withasync.each
:If you want to use a result from each iteration, then
async.map
is similar, but passes an array of results to the second argument of the callback.If you prefer vanilla JS, then this will work in place of
async.each
:(taken from a gist I wrote a while back)
I strongly suggest that you use the async library however. Async is fiddly to write, and functions like
async.auto
are brilliant.A possible simple JS solution would be to do something like this.
Update: Probably a better Javascript solution would be to use Promises