2

我在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);
    });
}
4

1 回答 1

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
    });
});

也就是说,对于您的特定示例,我宁愿使用 aJOIN并在 SQL 中处理它:

SELECT * FROM imbarcazioni
LEFT JOIN storico_imbarcazoni ON storico_imbarcazoni.id_imbarcazione = imbarcazioni.id
于 2012-04-20T11:34:14.253 回答