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

时间:2015-09-17 20:35:21

标签: javascript node.js asynchronous node-mysql

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

1 个答案:

答案 0 :(得分:0)

在第二个函数中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);
        });
    })
}