【问题标题】:Async.waterfall not passing callback for nested mysql queries?Async.waterfall 没有为嵌套的 mysql 查询传递回调?
【发布时间】:2015-09-18 15:04:24
【问题描述】:

我有一系列嵌套的 mysql 查询,我需要连续执行,因为后面的查询依赖于早期查询的结果 - async.waterfall 似乎是完美的解决方案。但是,瀑布的第二步未能将其结果附加到我的数组中:

async.waterfall([
function(callback) {
    connection.query(query, function(err, rows, fields) {
        if (err) throw err;

        var top_ten_publishers = [];
        rows.forEach(function (result) {
            var publisher_row = [result.name, result.sale_amount, result.actual_commission, result.transactions, result.post_date, result.toolbar_id, result.shop_source];

            top_ten_publishers.push(publisher_row);
        })
        callback(null, top_ten_publishers);
    })
},
function(top_ten_publishers, callback) {
    top_ten_publishers.forEach(function (publisher_row) {
        connection.query(“select  sum(sale_amount) as 'sale_amount', sum(actual_commission) as 'actual_commission', count(*) as transactions, from table where mall_name = '" + publisher_row[0] + "' and fc_post_date between '" + start_date_wow + "' and '" + end_date_wow + "' Group by name order by sum(sale_amount) desc;", function (err, rows, fields) {
            rows.forEach(function (result) {
                var wow = (publisher_row[3] - result.sale_amount) / result.sale_amount;
                publisher_row.unshift(wow);
            })
        });
    })
    callback(null, top_ten_publishers);
}
], function (err, result) {
    console.log(result);
});

如果我将 console.log 放在瀑布的第二步中,我会看到新值正确地添加到数组中,但是当最后一步运行时,新值不在数组中。我是否在第二步中做一些异步操作,让回调在查询运行之前被调用?

【问题讨论】:

    标签: javascript node.js asynchronous node-mysql


    【解决方案1】:

    在您的第二个函数中,top_ten_publishersforEach 在迭代完成后在每次迭代中进行异步调用,然后函数退出。由于无法保证对 async.query 的异步调用也已完成,因此您最终会得到混乱的结果。

    试试这个修改版的top_ten_publishers

    function(top_ten_publishers, callback) {
        top_ten_publishers.forEach(function (publisher_row) {
            connection.query(“select  sum(sale_amount) as 'sale_amount', sum(actual_commission) as 'actual_commission', count(*) as transactions, from table where mall_name = '" + publisher_row[0] + "' and fc_post_date between '" + start_date_wow + "' and '" + end_date_wow + "' Group by name order by sum(sale_amount) desc;", function (err, rows, fields) {
                rows.forEach(function (result) {
                    var wow = (publisher_row[3] - result.sale_amount) / result.sale_amount;
                    publisher_row.unshift(wow);
                })
                callback(null, top_ten_publishers);
            });
        })
    }
    

    【讨论】:

    • 你说得对——我发誓我确实试过了,但效果很好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 2014-02-08
    • 2018-10-22
    • 2017-05-03
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多