如何在Object值的异步for循环完成执行后调用函数

Set*_*ino 2 javascript ajax asynchronous node.js

我想在异步for循环之后调用一个函数,迭代Javascript对象的值完成执行.我有以下代码

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));
}
Run Code Online (Sandbox Code Playgroud)

qub*_*yte 6

这可以在vanilla JS中完成,但我推荐使用该async模块,这是用于处理Node.js中异步代码的最流行的库.例如,用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.
});
Run Code Online (Sandbox Code Playgroud)

如果要使用每次迭代的结果,则async.map类似,但将结果数组传递给回调的第二个参数.

如果您更喜欢vanilla JS,那么这将取代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();
}
Run Code Online (Sandbox Code Playgroud)

(取自我写的一段时间的要点)

我强烈建议您使用异步库.Async很难写,而且功能async.auto很棒.