Node.js 最终回调没有显示任何结果
我使用async series运行2个函数Node.js 最终回调没有显示任何结果,node.js,asynchronous,Node.js,Asynchronous,我使用async series运行2个函数需要2秒和函数需要5秒。为什么最终回调没有显示任何结果 var async = require('async'), operations = []; operations.push(takes2Seconds(1,function(){})); operations.push(takes5seconds(2,function(){})); async.series(operations, function (err, results) { if(e
需要2秒
和函数需要5秒
。为什么最终回调没有显示任何结果
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);
}
首先执行takes2Seconds函数,然后执行函数takes5seconds
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);
}
看起来您正在
将两个未定义的值推送到操作
运行async.series
时,操作
数组需要包含参数为回调
的函数
当您执行operations.push时(需要2秒(1,function(){}))
您正在直接调用takes2Seconds
函数,因为takes2Seconds
函数中没有return
语句,所以它是push
ingundefined
到操作数组
下面,我在takesXSeconds函数中添加了一个return
语句。现在,它们返回一个带有callback
作为参数的函数,返回的函数被推送到operations
数组中
我还从takesXSeconds中删除了回调
参数,因为此时不需要它
现在运行async.series(…)
时,将调用每个函数(我们从takesXSeconds返回的函数)
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);
}
}
你能详细说明一下吗explanation@aryankanwar我补充了一个解释。希望这能解释。如果您需要进一步的帮助,请告诉我。当我编写回调(null,result)时,这还不够返回吗?为什么要创建一个returninf函数并将callback作为其参数传递,然后最终调用其中的回调?您需要根据async
文档提供callback作为第一个参数。我在回答中提供了另一个例子。当async.series运行时,它会将一个函数传递给takesXSeconds函数,因此需要callback
param。但我还需要传递参数