我正在尝试使用NodeJS从MySQL INSERT查询中存储affectedRows的详细信息。我的思绪正在融化,试图理解回调和承诺。作为一个单人开发团队,我想联系并询问关于如何在foreach循环中应用回调的最清楚的解释。
从这几行代码中可以清楚地看到目标;将数据存储在affected_rows []数组中。
var affected_rows = [];
asset_array.forEach(function(asset) { // Populate the asset table
var query_string = "INSERT IGNORE INTO " + asset_table + " SET symbol = '" + asset[0] + "', name = '" + asset[1] + "'";
connection.query(query_string, function(err, rows, fields) {
if (err) throw err;
if ( rows.affectedRows > 0 ) {
data_to_push = [asset_table, asset[0], asset[1]];
affected_rows.push(data_to_push);
}
});
});
console.log(affected_rows); // [] for obvious async reasons
答案 0 :(得分:2)
一个选项是在函数内处理asset_array并将回调传递给它,当循环通过asset_array时,检查当前索引是否与asset_array长度(-1)匹配。如果是,请拨打回叫。
var affected_rows = []; function processAssets(cb) { var array_len = asset_array_len.length asset_array.forEach(function(asset, index) { var query_string = 'INSERT IGNORE INTO ' + asset_table + ' SET symbol = \'' + asset[0] + '\', name = \'' + asset[1] + '\''; connection.query(query_string, function(err, rows, fields) { if (err) throw err if (rows.affectedRows > 0) { data_to_push = [asset_table, asset[0], asset[1]]; affected_rows.push(data_to_push); } if (index === (array_len - 1)) cb() }); }); } processAssets(function() { console.log(affected_rows) })
答案 1 :(得分:0)
建议您查看异步Queue。
您可以像这样更改代码以使用它。
//2nd Step - Perform each task and then call callback() to move to next task
var q = async.queue(function(query_string, callback) {
connection.query(query_string, function(err, rows, fields) {
if (err) throw err;
if ( rows.affectedRows > 0 ) {
data_to_push = [asset_table, asset[0], asset[1]];
affected_rows.push(data_to_push);
}
callback(); //call next task
});
}, 2); //here 2 means concurrency ie 2 tasks will run in parallel
//Final Step - Drain gives you end of queue which means all tasks have finished processing
q.drain = function() {
//Do whatever you want after all tasks are finished
};
//1st Step - create a queue of all tasks that you need to perform
for (var i = 0; i < asset_array.length ; i++) {
var query_string = "INSERT IGNORE INTO " + asset_table + " SET symbol = '" + asset[0] + "', name = '" + asset[1] + "'";
q.push(query_string);
}