简体   繁体   English

Async-WaterFall无法正常工作

[英]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. 第一个调用了mongodb.find()。 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(): 这是被调用的两个函数:getAllBlogs():

exports.getAllBlogs = function() {

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

      });
}

seperateBlogs(): 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. 重要的是,在getAllBlogs()返回theBlogs之前不会调用seperateBlogs,但是在返回值之前将调用它。 I used Async_Waterfall to avoid this problem but it keeps recurring, which means I am using it wrong. 我使用Async_Waterfall来避免此问题,但它会不断发生,这意味着我使用错误。 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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