node如何做同步?
nodejs搭配mysql数据库,代码如下:
connection.query('select * from reply r,article a where r.aid = a.aid and parentId=""',function(err,ress){
if(err) console.log(err);
else
{
var j=0;
for(var i=0;i<ress.length;i++){
connection.query('select * from reply where parentId="'+ress[i].rid+'"',function(err,ress2){
if(err) console.log('查询失败');
else{
console.log(j);
ress[j++].reply = ress2;
}
})
}
console.log(ress);
connection.end();
}
但是打印出来的结果reply属性为空,检测到位异步请求造成的,请问如果做同步?
node.js nodejs爬虫 前端 web前端开发 前端工程师
蓝大人浏览器
11 years, 11 months ago
Answers
用 async
async = require('async');
async.map(ress, function(item, callback) {
connection.query('select * from reply where parentId="' + item.rid + '"', function(err, reply) {
if (err) {
return callback(err);
}
item.reply = reply;
return callback(null, item);
});
}, function(err, ress) {
return console.log(ress);
});
7UP☆波
answered 11 years, 11 months ago