I am new to this node.js ..I am little bit confused about this callback..In my app inside a for loop i am calling a asynchronous function call,i think my problem is that before i am getting response of async call my for loop get looped.
My code:
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));
});
}
Search function code:
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);
})
I want to execute for loop after successful execution of 1 search function, I think I have to use async for loop.