Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  18] [ 2]  / answers: 1 / hits: 6183  / 10 Years ago, thu, february 20, 2014, 12:00:00

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));
}

More From » ajax

 Answers
4

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, with async.each:



var async = require('async');

var courseIds = Object.keys(courses);

// Function for handling each course.
function perCourse(courseId, callback) {
var course = courses[courseId];

// do something with each course.
callback();
}

async.each(courseIds, perCourse, function (err) {
// Executed after each course has been processed.
});


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:



function each(list, func, callback) {
// Avoid emptying the original list.
var listCopy = list.slice(0);

// Consumes the list an element at a time from the left.
// If you are concerned with overhead in using the shift
// you can accomplish the same with an iterator.
function doOne(err) {
if (err) {
return callback(err);
}

if (listCopy.length === 0) {
return callback();
}

var thisElem = listCopy.shift();

func(thisElem, doOne);
}

doOne();
}


(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.


[#47541] Thursday, February 20, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
analiseb

Total Points: 252
Total Questions: 96
Total Answers: 106

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
analiseb questions
;