Exiting a callback function in node.js
I have a javascript array like:
[[1,2,3], [4,5,6]]
1,2,3 and 4,5 and 6 are my id's After the search completes. I want to send the output to the browser.
Can anyone tell me how can I exit or send the result to the browser?
for(var i = 0; i<idName.length; i++ ) {
tempJson = {user_id: followerId, feed_content_text: finalFeedText };
notifications.push(tempJson);
var conditions = {
user_id: followerId,
external_id: key
};
FeedModel.findOne(conditions, function (err, data) {
//What condition should i write to send the output to browser when, it is done for all 'idNames'
res.send({
success: true,
message: finalMsgs
});
});
}
+3
source to share
3 answers
Have you tried the following:
var result = [];// initialize result array
for(var i = 0; i<idName.length; i++ ) {
tempJson = {user_id: followerId, feed_content_text: finalFeedText };
notifications.push(tempJson);
var conditions = {
user_id: followerId,
external_id: key
};
FeedModel.findOne(conditions, function (err, data) {
result.push(data);//storing data in result
if((i+1) === idName.length) { // check if all is completed
res.send({ // sending response
success: true,
message: finalMsgs,
data: result
});
}
});
}
+2
source to share
This works great in my case:
var userIndex = 0;
for(var i = 0; i<idName.length; i++ ) {
userIndex++;
tempJson = {user_id: followerId, feed_content_text: finalFeedText
};
notifications.push(tempJson);
var conditions = {
user_id: followerId,
external_id: key
};
FeedModel.findOne(conditions, function (err, data) {
userIndex--; // It'll be 0 at the end
if ( userIndex == 0 ) {
return res.send({
success: true,
message: finalMsgs
});
}
});
}
+1
source to share