1
\$\begingroup\$

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.");
 }
 });
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 9, 2014 at 8:52
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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();
answered Jan 9, 2014 at 13:32
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.