最终回调未显示任何结果

时间:2017-02-01 10:19:48

标签: node.js asynchronous

我正在使用异步系列运行2个函数takes2Seconds和函数takes5Seconds。为什么最终的回调没有显示任何结果?

var async = require('async'),
operations = [];

operations.push(takes2Seconds(1,function(){}));
operations.push(takes5seconds(2,function(){}));

async.series(operations, function (err, results) {
 if(err){return err;}
 console.log(results);
});



function takes2Seconds(a,callback) {

    results='Took 2 sec'+a;
    callback(null, results);
}

function takes5seconds(b,callback) {
    results='Took 5sec'+b;
    callback(null, results);
}

2 个答案:

答案 0 :(得分:0)

首先执行take2Seconds函数,然后执行函数执行5秒。

 var takes2Seconds = function (a, callback) {//first this function executed
        results = 'Took 2 sec' + a;
        callback(null, results);
    };
    async.eachSeries(takes2Seconds, takes5seconds, function (err) {
        if (err) {
            res.json({status: 0, msg: "OOPS! How is this possible?"});
        }
        res.json("Series Processing Done");
    })
    var takes5seconds = function (b, callback) { // second this function executed
        results = 'Took 5sec' + b;
        callback(null, results);
    }

答案 1 :(得分:0)

您似乎push将两个未定义的值operations async.series

运行operations时,callback数组需要包含operations.push(takes2Seconds(1, function() {}));作为参数的函数。

执行takes2Seconds时,您正在立即调用return函数,并且由于takes2Seconds函数中没有push语句,因此undefined } return到操作数组。

下面,我在takeXSeconds函数中添加了callback语句。它们现在返回一个以operations为参数的函数,返回的函数被推送到callback数组。

我还从takesXSeconds中删除了async.series(...) param,因为此时不需要它。

现在运行var async = require('async'), operations = []; operations.push(takes2Seconds(1)); operations.push(takes5seconds(2)); async.series(operations, function (err, results) { if(err){return err;} console.log(results); }); function takes2Seconds(a) { var results='Took 2 sec'+a; return function(callback) { callback(null, results); } } function takes5seconds(b) { var results='Took 5sec'+b; return function(callback) { callback(null, results); } } 时,会调用每个函数(我们从takeXSeconds返回)。

val words = readme.flatMap(line => line.split(" ")).collect()