Node.js async parallel TypeError:task不是函数

时间:2016-04-17 17:11:21

标签: javascript node.js asynchronous async.js

我正在使用异步模块来执行并行任务。基本上我有两个不同的文件,dashboard.js和Run.js.

Dashboard.js

module.exports = {

    func1 : function(){
        console.log(“Funtion one”);

    },
    func2 : function(){
        console.log(“Funtion two”);
    }

}

Run.js

    var dashboard = require(‘dashboard.js’);

    var async = require('async');

    async.parallel([dashboard.func1, dashboard.func2],function(err){
        if(err)throws err;
        console.log(“ All function executed”);
   });

我期待func1和func2并行执行,但它会抛出错误

TypeError: task is not a function
    at C:\Users\..\java\realtime-preview\node_modules\async\lib\async.js:718:13
    at async.forEachOf.async.eachOf (C:\Users\..\java\realtime-preview\node_modules\async\lib\async.js:233:13)
    at _parallel (C:\Users\\java\realtime-preview\node_modules\async\lib\async.js:717:9)

为什么我不能使用 dashboard.func1,dashboard.func2 甚至dashboard.func1都是函数?

1 个答案:

答案 0 :(得分:1)

对于async属性,我会使用回调功能。此功能还有利于非阻塞呼叫。

使用您的代码,您可以尝试

Dashboard.js

module.exports = {
   func1 : function(callback){
       var value = “Function one”;

       //if value happens to be empty, then undefined is called back
       callback(undefined|| value);
   },
   func2 : function(callback){
       var value = “Function two”;

       //if value happens to be empty, then undefined is calledback
       callback(undefined|| value);
   }
}

Run.js

var dashboard = require(‘dashboard.js’);

   //func1
   dashboard.func1(function(callback){

     //if callback then do the following
     if(callback){
         console.log(callback);

     //if no data on callback then do the following
     }else{
         console.error('Error: ' + callback);
     }
   });

   //func2
   dashboard.func2(function(callback){

      //if callback then do the following
     if(callback){
         console.log(callback);

     //if no data on callback then do the following
     }else{
         console.error('Error: ' + callback);
     }
   });
});

在以下链接中还有一个与您类似的问题:Best way to execute parallel processing in Node.js

此外,错误的具体答案在以下链接中: TypeError: task is not a function in async js parrallel