使异步.瀑布式从另一个函数的参数开始

make async.waterfall start with argument from another function

本文关键字:函数 参数 开始 另一个 异步 布式      更新时间:2023-09-26

我遇到了一个我似乎无法解决的问题。这是一个蒸汽交易机器人,它工作得很好,除了当两个人在同一时间与它交易,因为class_id和other_id是全局变量,他们会在一个交易的中间改变,如果多于一个使用它。

我尝试在最后一个if语句中定义变量,但get_class_id没有找到变量。是否有任何方法异步函数可以取item。直接分类和convert_id_64(offer.accountid_other)而不将它们定义为变量?谢谢你的帮助。

var class_id
var other_id
function accept_all_trades(offers_recieved) {
offers_recieved.forEach( function(offer) {
    if (offer.trade_offer_state == 1) {
        if (typeof offer.items_to_give === "accept") {
            offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function(error, response) {
                console.log('accepterat offer');
                offer.items_to_receive.forEach(function(item) {
                    if (item.appid === '420') {
                        class_id = item.classid;
                        other_id = convert_id_64(offer.accountid_other);
                        console.log(class_id);
                        async.waterfall([get_class_id, get_stack, get_name, get_save], add_names);
                    }
                });
            });
        }
    }
});
}
function get_class_id(callback) {
var test = class_id
callback(null, test)
}

更新

我已经改变了代码是什么建议,但仍然当我调用get_class_id并尝试打印id它只是一个空白行在控制台,任何想法?

function get_class_id(callback) {
console.log(class_id);
var test = class_id;
callback(null, test)
}

这里的问题不是aysnc.waterfall()。这是async调用(offers.acceptOffer(), get_class_id, get_stack, get_name, get_save, add_names)在常规javascript forEach()。您需要能够控制这些异步调用流的控制流循环。下面是使用async.each():

修改后的代码
function accept_all_trades(offers_recieved) {
    async.each(offers_recieved, function(offer, eachCb) {
        if (offer.trade_offer_state !== 1 || typeof offer.items_to_give !== "accept") {
            return eachCb(null);
        }
        offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function(error, response) {
            console.log('accepterat offer');
            async.each(offer.items_to_receive, function(item, eachCb) {
                var class_id;
                var other_id;
                if (item.appid !== '420') {
                    return eachCb(null);
                }
                class_id = item.classid;
                other_id = convert_id_64(offer.accountid_other);
                console.log(class_id);
                async.waterfall([
                    function(waterfallCb) {
                        var test = class_id;
                        console.log(class_id);
                        waterfallCb(null, test);
                    },
                    get_stack,
                    get_name,
                    get_save,
                    add_names
                ], eachCb);
            }, function(err) {
                console.log(err);
                eachCb(null);
            });
        });
    });
}