我是这个 node.js 的新手..我对这个回调有点困惑..在我的应用程序中的 for 循环中,我正在调用异步函数调用,我认为我的问题是在我收到异步调用的响应之前for 循环被循环。
我的代码:
async.forEach(Object.keys(config), function(key, next) {
search(config[key].query, function(err, result) { //
console.log("fffffffffff="+ util.inspect(result))-------- >>>Getting undefined..
if (err) return next(err) //
var json = JSON.stringify({
"result": result
});
results[key] = {
"result": result
}
console.log("rrrrrrrr="+util.inspect(results[key]))
next() // <---- critical piece. This is how the forEach knows to continue to the next loop. Must be called inside search's callback so that it doesn't loop prematurely.
})
},
function(err) {
console.log('iterating done');
res.writeHead(200, {
'content-type': 'application/json'
});
res.end(JSON.stringify(results));
});
}
搜索功能代码:
var matches = [];
var qrySubString = query.substring(0, 4);
client.query("select * from xxxxxxxxx where level4 ILIKE '%" + query + "%'", function(err, row1, fields) {
for (var id in row1.rows) {
var match, name;
if (query == row1.rows[id].level4) {
match = true;
name = row1.rows[id].level4;
}
else {
match = false;
name = query;
}
matches.push({
"id": id,
"name": row1.rows[id].level4,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
})
}
callback(matches);
})
我想在成功执行 1 个搜索函数后执行 for 循环,我想我必须使用 async for 循环。请指导我解决这个问题..提前谢谢..