[英]node.js async.series is that how it is supposed to work?
var async = require('async');
function callbackhandler(err, results) {
console.log('It came back with this ' + results);
}
function takes5Seconds(callback) {
console.log('Starting 5 second task');
setTimeout( function() {
console.log('Just finshed 5 seconds');
callback(null, 'five');
}, 5000);
}
function takes2Seconds(callback) {
console.log('Starting 2 second task');
setTimeout( function() {
console.log('Just finshed 2 seconds');
callback(null, 'two');
}, 2000);
}
async.series([takes2Seconds(callbackhandler),
takes5Seconds(callbackhandler)], function(err, results){
console.log('Result of the whole run is ' + results);
})
輸出如下所示:
Starting 2 second task
Starting 5 second task
Just finshed 2 seconds
It came back with this two
Just finshed 5 seconds
It came back with this five
我期待take2Second函數在take5Second開始之前完全完成。 它是如何工作的。 請告訴我。 而最終的功能永遠不會運行。 謝謝。
不完全的。 您正在立即執行這些功能(一旦評估了數組),這就是它們似乎同時啟動的原因。
傳遞給要執行的每個函數的回調是異步庫的內部。 一旦函數完成,執行它,傳遞錯誤和/或值。 您不需要自己定義該功能。
最后的函數永遠不會在你的情況下運行,因為異步需要你調用以回到系列中的下一個函數的callbackHandler
函數永遠不會實際執行(只有你的callbackHandler
函數被執行)。
試試這個:
async.series([
takes2Seconds,
takes5seconds
], function (err, results) {
// Here, results is an array of the value from each function
console.log(results); // outputs: ['two', 'five']
});
James為您提供了async.series
概述。 請注意,您可以在系列數組中設置匿名函數,然后使用參數調用實際函數
var async = require('async')
var param1 = 'foobar'
function withParams(param1, callback) {
console.log('withParams function called')
console.log(param1)
callback()
}
function withoutParams(callback) {
console.log('withoutParams function called')
callback()
}
async.series([
function(callback) {
withParams(param1, callback)
},
withoutParams
], function(err) {
console.log('all functions complete')
})
我創建異步系列的首選方法是使用操作數組,如下所示;
var async = require('async'),
operations = [];
operations.push(takes2Seconds);
operations.push(takes5seconds);
async.series(operations, function (err, results) {
// results[1]
// results[2]
});
function takes2Seconds(callback) {
callback(null, results);
}
function takes5seconds(callback) {
callback(null, results);
}
async.series
([
function (callback)
{
response=wsCall.post(user,url,method,response);
console.log("one");
callback();
}
,
function (callback)
{
console.log("two");
//console.log(response);
callback();
}
]
,
function(err)
{
console.log('Both a and b are saved now');
console.log(response);
});
在async.series
,所有函數都是串行執行的,每個函數的統一輸出都傳遞給最終的回調函數。 例如
var async = require('async');
async.series([
function (callback) {
console.log('First Execute..');
callback(null, 'userPersonalData');
},
function (callback) {
console.log('Second Execute.. ');
callback(null, 'userDependentData');
}
],
function (err, result) {
console.log(result);
});
輸出:
First Execute..
Second Execute..
['userPersonalData','userDependentData'] //result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.