I am using the Q promise library for making database calls. But before promise inside first then() completes, the second then() promise is started. The code is as follows:
var promise = Q.nfcall(function(){});
promise.then(removeFromOldList(data))
.then(addToNewList(data))
.done();
function removeFromOldList(data) {
console.log('removeFromOldList');
// remove the card from old list
DB.ListTable.findOne({ _id : data.oldId},
function(err, snippet) {
if(err) console.error("An error occurred");
if (err) console.error(err);
console.log('removed the card from old list');
})
}
function addToNewList(data) {
console.log('addToNewList');
// add the card to the new list
DB.ListTable.findOne({ _id: data.newId},
function(err, snippet) {
if(err) console.error("An error occurred");
if (err) console.error(err);
console.log('add the card to the new list');
})
}
The console log gives me:
removeFromOldList
addToNewList
removed the card from old list add the
card to the new list
How can i make the callbacks be executed before the promise is returned.
The problem is the DB.ListTable.findOne calls are asynchronous, so node will go through both functions before even hitting the DB callbacks.
Can you try something like this:
var query1 = DB.ListTable.findOne({ _id : data.oldId}, function(err, snippet) {
...
}).exec();
var query2 = DB.ListTable.findOne({ _id: data.newId}, function(err, snippet) {
...
}).exec();
var promise = Q.nfcall(function(){});
promise
.then(query1)
.then(query2)
.done();