繁体   English   中英

未定义异步并行回调

[英]async parallel callback is not defined

尝试使用async.parallel时出现错误“未定义回调”,但是我为什么无法使用。 async.parallel的所有示例均具有内联函数(例如async doco https://caolan.github.io/async/docs.html#parallel ),但是由于我要运行的函数中包含一些逻辑,因此我尝试了拆分它们,使它们不内联。 这可能是我的问题,但我认为应该可行,我无法从示例中弄清楚在这种情况下回叫应该如何工作。

然后,这里的意图是让两个函数从不同位置获取ID列表,然后将它们放在一起并在结果数组上做一些事情。 我已经修剪了“执行其他操作”,因为在此阶段它似乎无关紧要。

var structuresIDArray = [];

function getPublicStructures(callback){
    request({
        url: 'https://esi.tech.ccp.is/latest/universe/structures/?datasource=tranquility',
        method: 'GET'
    }, function (error, response, body) {
        if(!error && !body.error && response.statusCode === 200){
            console.log('getting public locations');
            structuresIDArray.concat(JSON.parse(body));
            callback(null, structuresIDArray);
        }else{
            callback(error);
        }
    });
}

function getAssetLocationList(callback){
    db.any('select distinct "location_id" from "public"."charassets" where "location_id" is not null')
    .then(function (data) {
        for (var i = 0; i < data.length; i++) {
            structuresIDArray.push(data[i].location_id);
            if(i+1===data.length){
                callback(null, structuresIDArray);
            }
        }

    })
    .catch(function (err) {
        callback(err);
    });
}



function main(){

    async.parallel([ getAssetLocationList(callback), getPublicStructures(callback) ],
        function (err, results) {
            if (err) {
                throw err;
            }
            // Go do some other stuff now ...
        });
}

当您调用它时,似乎变量“ callback”不在范围内。 尝试将其添加到这些函数的参数列表中。

喜欢:

function (error, response, body, callback)
...
function (data, callback)

您需要提供函数数组以与async.parallel并行执行,因此您需要执行以下操作

    async.parallel([getAssetLocationList,getPublicStructures],function(err, results) {
       //This callback executes when both the above functions have called their respective callbacks.
       //results[0] will contain data from getAssetLocationList
       //results[1] will contain data from getPublicStructures
    });

基本上所有我改变是getAssetLocationList(callback) ,只是getAssetLocationListgetPublicStructures(callback) ,以getPublicStructures在主函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM