Async.waterfall 没有传递嵌套 mysql 查询的回调?

Async.waterfall not passing callback for nested mysql queries?

我有一系列嵌套的 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,我会看到新值被正确地添加到数组中,但是当最后一步 运行 时,新值是' 在数组中。我是否在第二步中做了一些异步操作,让回调在查询 运行?

之前被调用

在您的第二个函数中,top_ten_publishers forEach 在迭代完成后在每次迭代中进行异步调用,然后函数退出。由于无法保证对 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);
        });
    })
}