【问题标题】:How to pass value of a function into a async.waterfall function如何将函数的值传递给 async.waterfall 函数
【发布时间】:2019-02-18 18:27:15
【问题描述】:

我的代码有问题。我想从 Mysql 表中选择并考虑结果,更改它并再次更新该表。问题是,代码是异步执行的,它不能正常工作(它首先执行所有 SELECT,然后执行所有 UPDATE)。所以我使用 async.js 来完成工作,但仍然无法正常工作。因为我无法将 Selected 值从调用者回调中传递出去。所以不可能通过 async.waterfall 将它传递给下一个回调。有什么想法吗?

async.waterfall([

    function (callback) {

        queryBuilder.selectAgent(connection, id, (agent) => {
            // Here is the PROBLEM! I can't pass agent out of this
        });

        // Here agent will be undefined
        callback(null, agent);
    },

    function (agent, callback) {

        if (agent) {
            // Some change on agent and pass it to next callback
        }

        callback(null, agent);
    },

    function (agent, callback) {

        queryBuilder.updateAgent(connection, id, agent);

        callback(null);
    },

],

function (err) {
    if (err) throw err;

})

【问题讨论】:

  • 为什么不在selectAgent回调中调用callbackl(null, agent)?像这样queryBuilder.selectAgent(connection, id, (agent) => callback(null, agent)); 注意:我不知道agent 对象的生命周期!
  • 因为它导致了我的第一名问题!如果我在 queryBuilder.selectAgent() 中调用 callback(null, agent),则所有 SELECT 将首先执行,然后所有 UPDATE 执行,我希望它们以这种方式运行 => SELECT, UPDATE, SELECT, UPDATE, ...

标签: javascript node.js async.js


【解决方案1】:

您需要更改updateAgent 方法以检查以前的值并向其中添加新数据,或者您可以先检查任何特定项目的更新并收集它们以更新该字段一次。

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 2010-09-25
    • 2018-04-04
    • 2014-02-08
    相关资源
    最近更新 更多