Kamal K Kamal K - 1 month ago 8
Node.js Question

control flow of callbacks with db returns in node js

I am newbie in node js and facing a problem with control flow of callbacks with db returns.

What I want is the following sequence:

console.log('>>>>>>> first log in F1 >>>>>>');
console.log('>>>>>>> second log in F1 >>>>>>');
console.log('>>>>>>> first log in F2 >>>>>>');
console.log('>>>>>>> second log in F2 >>>>>>');
console.log('>>>>>>> first log in F3 >>>>>>');
console.log('>>>>>>> second log in F3 >>>>>>');
console.log('>>>>>>> first log in F4 >>>>>>');
console.log('>>>>>>> second log in F4 >>>>>>');
console.log('>>>>>>> third log in F4 >>>>>>');
console.log('finished ');


But I am not gettting in that order. Code looks like as follows:

F1(req).then(function(result){
return F2(result);
}).then(function(result){
return F3(result);
}).then(function(result){
return F4(result);
}).then(function(result){
console.log('finished ');
})

var F1 = function(req) {
return new Promise(function(resolve, reject) {
console.log('>>>>>>> first log in F1 >>>>>>');
var result = {};
result.emailId = req.body.emailId;
common.db.collection('document1').findOne({email: req.body.emailId}, function (error, document1object) {
console.log('>>>>>>> second log in F1 >>>>>>');
});
resolve(result);
});
};
var F2 = function(result) {
console.log('>>>>>>> first log in F2 >>>>>>');
return new Promise(function(resolve, reject) {
common.db.collection('document2').findOne({email: result.emailId}, function (err, document2object) {
console.log('>>>>>>> second log in F2 >>>>>>');
result.value1 = document2object._id;
});
resolve(result);
});
};
var F3 = function(result) {
console.log('>>>>>>> first log in F3 >>>>>>');
return new Promise(function(resolve, reject) {
common.db.collection('document3').insertOne({email: result.emailId}, function (errr, document3object) {
console.log('>>>>>>> second log in F3 >>>>>>');
result.value2 = document3object.insertedId;
});
resolve( result);
});
};
var F4 = function(result) {
console.log('>>>>>>> first log in F4 >>>>>>');
return new Promise(function(resolve, reject) {
client.post("urlPart1"+result.value2+"urlPart2",
args, function (data, response) {
console.log('>>>>>>> second log in F4 >>>>>>');
});
console.log('>>>>>>> third log in F4 >>>>>>');
resolve( result);
});
};


Thank you in advance :)

Answer

Because... async.

Your request get all evaluated at the same time, thus you're not getting the log in the order you want. If you want a specific order, you'll have to start the next request when the last one is done, i.e. in the callback function of the previous one.