To catch errors, I have written if-else blocks in every function which looks bad. Please suggest a better way to handle errors in async node.
async.waterfall([
function(callback){
fnOne.GetOne(req, res,function(err,result) {
if(err){
console.error("Controller : fnOne",err);
callback(err,null);
}
else{
var fnOne = result;
callback(null, fnOne);
}
})
},
function(fnOne, callback){
fnTwo.two(fnOne,function(err,result) {
if(err) {
console.error(err);
callback(err,null);
}
else{
callback(null, context);
}
})
}
], function (err, result) {
if(err){
console.error("Controller waterfall Error" , err);
res.send("Error in serving request.");
}
});
1 Answer 1
Check out promises. They are not (yet) available natively in Node.js, but you can use Q library.
Promises allow you to make your control flow explicit with methods like catch
and finally
instead of hiding it in callbacks.
Also you won't need async
with promises.
Q provides a convenience method to "convert" a function that accepts a callback to a promise-returning function.
I don't understand what fnOne
or fnTwo
is your code (seemingly objects and not functions), so I can't really translate your example, but it would look similar to this:
var Q = require('q');
// Convert our functions to promise-returning functions
var getOne = Q.nbind(fnOne.GetOne, fnOne),
getTwo = Q.nbind(fnTwo.two, fnTwo) ;
getOne(req, res)
.then(function (result) {
return getTwo(result);
})
.then(function (result) {
// do something useful with final result
})
.catch(function (err) {
console.error("Three was an error", err);
res.send("Error in serving request.");
})
.done();