Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

javascript - How to call a function after an asynchronous for loop of Object values finished executing

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));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...