Node.js 同步循环或迭代异步语句

10 浏览
0 Comments

Node.js 同步循环或迭代异步语句

我想要使用一个for each循环,但希望它以同步方式运行。循环的每次迭代都会执行一个http.get调用,并将返回的json插入数据库中。问题在于for循环是异步运行的,导致所有的http.get调用同时进行,我的数据库没有插入所有的数据。我正在尝试使用async-foreach来实现我想要的效果,但如果有正确的方法可以实现,我就不必使用它。

mCardImport = require('m_cardImport.js');

var http = require('http');

app.get('/path/hi', function(req, res) {

mCardImport.getList(function(sets) {

forEach(sets, function(item, index, arr) {

theUrl = 'http://' + sets.set_code + '.json';

http.get(theUrl, function(res) {

var jsonData = '';

res.on('data', function(chunk) {

jsonData += chunk;

});

res.on('end', function() {

var theResponse = JSON.parse(jsonData);

mCardImport.importResponse(theResponse.list, theResponse.code, function(theSet) {

console.log("SET: " + theSet);

});

});

});

});

});

});

我的模型:

exports.importResponse = function(cardList, setCode, callback) {

mysqlLib.getConnection(function(err, connection) {

forEach(cardList, function(item, index, arr) {

var theSql = "INSERT INTO table (name, code, multid, collector_set_num) VALUES "

+ "(?, ?, ?, ?) ON DUPLICATE KEY UPDATE id=id";

connection.query(theSql, [item.name, setCode, item.multid, item.number], function(err, results) {

if (err) {

console.log(err);

};

});

});

});

callback(setCode);

};

0