request-json 的多个 get 请求在节点 js 中的异步执行不正确

Multiple get requests with request-json not executing properly with async in node js

我的要求是我需要从多个 REST 资源加载 JSON 数据。为此,我需要发出多个获取请求。当所有请求都完成后,我需要执行一些功能。

下面是我的代码:

var asyncTasks = [];
//These URLs are dynamic and can increase or decrease
var urls = ["resource1", "resource2", "resource3"];
var client = request.createClient("domainurl");

urls.forEach(function (item) {
    asyncTasks.push(function () {
        client.get(item, function (err, res, body) {
            dataLoaded(err, res, body)
        });
    });
});

async.parallel(asyncTasks, function () {
    // All tasks are done now
    allDataLoaded();
});

function dataLoaded(err, res, body) {
console.log('Data Loaded');
};

function allDataLoaded() {
console.log("All data loaded");
}

我面临的问题是 allDataLoaded 函数没有被调用,尽管 dataLoaded 函数被正确调用。

我正在为此使用 request-json 和异步 npm 包。 感谢您抽出时间,如果需要任何其他信息,请告诉我。

async.parallel 将回调传递给您需要调用的每个任务,否则它无法知道您的任务何时完成。使用

var asyncTasks = urls.map(function (item) {
    return function (cb) {
//                   ^^
        client.get(item, function (err, res, body) {
            dataLoaded(err, res, body)
            cb(err);
//          ^^^^^^^
        });
    };
});

那么 async.parallel(asyncTasks, allDataLoaded) 就可以了。