I am new to nodejs and struggling to find the issue with the below piece of code.
All i am trying to achieve is, calling few methods one after other and if all the calls are successful, then return success else throw an error if any of the method fails.
Issue i have is, before all the method gets executed, the main method terminates even though the promises are yet to be fullfilled.
Main method
processRequest(neworder).then(function (done) {
console.log('Successfully processed the order' + done);
res.sendStatus(200);
}).fail(function (error) {
res.status(404).send(error);
})
Other method calls
module.exports.processRequest = function (Order) {
var deferred = Q.defer();
findX(Order)
.then(findYBasedOnPrevOutput)
.then(findZBasedOnPrevOutput)
.then(deferred.resolve())
.fail(function (err) {
console.log('Failed to process request' + err);
deferred.reject(err);
});
return deferred.promise;
}
var findX = function (order) {
var deferred = Q.defer()
db.list(order, function (address) {
console.log('Query success');
if (address == null)
deferred.reject('Error');
else {
deferred.resolve(address);
}
})
return deferred.promise;
};
Issue that i am having is, i see in the console the success just after the findX method gets called. I expected the success msg after findZ method.
Can you please help me in finding the issue with the above code, appreciate your input/suggestions in this regard
For simplicity, i didn't share the other modules here, but they are very similar to findX
setTimeout(fn(), 100)instead ofsetTimeout(fn, 100). Also, you're doing explicit construction: stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it