简体   繁体   中英

Async-WaterFall not working as expected

waterfall function with two calls but the second on is not waiting for the first one to completely finish. The first one has a mongodb.find() call in it. Here is the async-waterfall function

app.get("/news", function(req, res) {
    async.waterfall([
         function (callback) {

            var blogs = tendigiEngine.getAllBlogs(callback);
            callback(null, blogs);
          },
          function (blogs, callback) {

            var array = tendigiEngine.seperateBlogs(blogs, callback);
            callback(null, array );
          }

     ], function (err, result) {
       // result now equals 'done'   
       console.log("done"); 
       console.log(result);
    });

});

Here are the two functions being called: getAllBlogs():

exports.getAllBlogs = function() {

    Blog.find(function(err, theBlogs){
        if(!err) {
            return theBlogs;
         }
        else {
                throw err;
        }

      });
}

seperateBlogs():

exports.seperateBlogs  = function(blogs) {

      if(blogs.length === 0 ) {
            return 0;
        }
        else {
             blogs.reverse();
             var blog  = blogs[0];
             blogs.shift(); 
             var finArray = [blog, blogs];
             return finArray;
        }
      console.log("asdf");
}

It is important that seperateBlogs won't be called before getAllBlogs() has returned theBlogs, but it is being called before the value is returned. I used Async_Waterfall to avoid this problem but it keeps recurring, which means I am using it wrong. What am I doing wrong here and how can I fix it?

Thanks!

Your exported functions are missing the callback parameters:

exports.getAllBlogs = function(cb) {
  Blog.find(cb);
};

exports.seperateBlogs = function(blogs, cb) {
    if (blogs.length === 0 )
      return cb(null, blogs);

    blogs.reverse();
    var blog = blogs[0];
    blogs.shift(); 
    cb(null, [blog, blogs]);
}

Then your main code can be simplified as well:

async.waterfall([
   tendigiEngine.getAllBlogs,
   tendigiEngine.seperateBlogs
], function (err, result) {
   // result now equals 'done'   
   console.log("done"); 
   console.log(result);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM