NodeJS中mysql查询的时序问题

时间:2012-04-20 10:50:25

标签: mysql node.js asynchronous timing

我在nodejs中使用mysql模块。

我想做类似的事情,但问题是查询的回调是异步的,我无法正确填充结果数组。我该怎么办?谢谢!

function fn(callback) {
    client.query(
        'SELECT * FROM imbarcazioni',
        function select(err, ships) {
        if(err) {
            throw err;
        }

        ships.forEach(function(ship) {
            client.query(
                'SELECT * FROM storico_imbarcazioni WHERE id_imbarcazione=' + ship.id,
                function select(err, hist) {
                    ship.history = hist;
                }
            );
        });

        callback(hist);
    });
}

1 个答案:

答案 0 :(得分:3)

像往常一样,我推荐async来做这些事情。在这里,您可以使用async.map

function selectHistory(ship, callback) {
    client.query('SELECT * FROM storico_imbarcazioni WHERE id_imbarcazione = ?', [ship.id], function(err, history) {
        if(err) return callback(err);
        ship.history = history;
        callback(null, ship);
    });
}

client.query('SELECT * FROM imbarcazoni', function(err, ships) {
    async.map(ships, selectHistory, function(err, ships) {
        // ships is an array with each ship along with it's history
    });
});

那就是说,对于你的特定例子,我宁愿使用JOIN并在SQL中处理它:

SELECT * FROM imbarcazioni
LEFT JOIN storico_imbarcazoni ON storico_imbarcazoni.id_imbarcazione = imbarcazioni.id