异步-回调不是函数 [英] Async - callback is not a function

查看:346
本文介绍了异步-回调不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在节点js中使用异步,以控制某些功能的执行流程.在下面的代码中,我有三个已声明的函数,应分别输出一个",两个"和三个"以及执行其他任务(打印仅是为了让我看到什么时候执行).

I am trying to work with async in node js, to control the flow of execution of some functions. In the code below I have three declared functions that should print respectively 'one', 'two' and 'three', along with performing other tasks (the printing is only so that I can see what gets executed when).

async.waterfall([
    function(callback) {
      settings();
      console.log("1");
      callback(null, 'one');
    },
    function(callback) {
      profile();
      console.log("2");
      callback(null, 'two');
    },
    function(callback) {
        console.log("3");
        groups();
        callback(null, 'two');
    }
  ]);

因此我在 callback(null,'two'); 行中收到错误消息"callback is a function"老实说,这也可能是一个非常虚假的问题,而且我还不完全了解异步瀑布的工作方式.但是我认真地尝试通过阅读示例来尝试实现短代码并尝试使用它.

So I get the error "callback is not a function" in the line of callback(null, 'two'); To be honest, this might as well be a very dummy question, and I do not fully understand how async waterfall works. But I seriously did try, by reading examples, trying to implement short code and trying to play around with it.

有趣的是,如果使用async.series而不是async.waterfall,则不会出现此类错误.但是async.series将打印1、2、3、3、1、2.瀑布模型中的数字是按顺序打印的,但是内部的功能未按正确的顺序执行.

Interesting that if async.series is used instead of async.waterfall, there is no such error. However async.series will print 1, 2, 3, three, one, two. The numbers inside the waterfall model are printed in sequence, but the functions inside are not executed in the right order.

请注意,前两个功能-设置和配置文件-包括数据库读取和计算,而第三个仅打印一些结果.

It is to be noted that the first two functions - settings and profile - include db reading and calculations whereas the third only prints some results.

推荐答案

使用 async.waterfall ,结果作为参数传递给下一个函数.例如:

With async.waterfall, results are passed to the next function as arguments. For example:

async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
        // arg1 now equals 'one' and arg2 now equals 'two'
        callback(null, 'three');
    },
    function(arg1, callback) {
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    // result now equals 'done'
});

在您的情况下,第二个函数上的 callback 将收到字符串 one 作为参数.因此,您遇到的错误.

In your case, callback on the second function will have received the string one as argument. And thus the error you are experiencing.

这篇关于异步-回调不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆