1

Disclaimer: new to JS and everything around it. :)

I was wondering if we could nest async functions within one another

I have a waterfall method in node:

/**
 * POST new travel wish
 */
router.post('/add', function(req, res) {
    var db = req.db;

    console.log(req.body);
    // add properties: customer_id and timestamp
    var date = new Date();
    //...

    var notif;

    async.waterfall(
      [
         // find the User
         function(next){
           db.collection(userCollection).findOne({_id: new ObjectId(req.session.userID)}, next);
         },

         // insert a new travelwish
         function(user, next){
           notif = {
             'username': user.username,
           };
           // TODO: add a async.parallel
           db.collection('travelwishlist').insert(req.body, next);
         },

         // setup timer for processing and send confirmation
         function(insertedTravelWish, next){
           NotificationManager.sendConfirmationNotification(notif);
           next(null, insertedTravelWish);         
         }
     ],

       // waterfall callback --> send http response.
       function (err, insertedTravelWish) {                  
         res.send(
           //if everything is ok the system sends the travel wish ID to the client otherwise error
           (err === null) ? { msg: insertedTravelWish[0]["_id"] } : { msg: 'err' }
         );
        }
     );
});

I want to insert multiple items instead of just one.

I think i can do this with parallel, but can I put it inside the existing waterfall?

1
  • i donT know.. i thought it d be messy and ppl would suggest a cleaner alternative.. Commented Jan 29, 2015 at 16:03

1 Answer 1

1

Yep, you totally can do it, here is some piece of example

async.waterfall([
    function (callback) {
        callback(null, 1);
    },
    function (arg, callback) {
        callback(null, arg1 + 1);
    },
    function (arg, callback) {
        async.parallel([
            function (_callback) { ... },
            function (_callback) { ... },
        ], finalCallback);
    }
]);

just a little tip, make sure you proivde different names for the callbacks (so you won't call the other one) if I've 2 nested functions that requires a callback most of the time I name them as callback _callback __callback

Sign up to request clarification or add additional context in comments.

2 Comments

cool! But, about the callbacks, why donT u make the changes in your answer? callback --> _callback
@Zortkun, I was sure its clear enough, there is many examples on async's github page. anyway the _callback should be the arg in the inside parallel functions.

Your Answer

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.