三個非同步函式 func1(13秒)、func2(5秒)、func3(1秒),需按順序執行:func1 → func2 → func3。直接呼叫會並行執行,輸出順序為 3→2→1。
var func1 = function(req, res, cb) { setTimeout(() => { console.log('func1'); cb(); }, 13000); };
var func2 = function(req, res, cb) { setTimeout(() => { console.log('func2'); cb(); }, 5000); };
var func3 = function(req, res, cb) { setTimeout(() => { console.log('func3'); cb(); }, 1000); };
func1(null, null, function() {
func2(null, null, function() {
func3(null, null, function() {
console.log('全部完成');
process.exit(0);
});
});
});
缺點:程式碼向右延伸、難以維護、錯誤處理分散、難以動態調整順序。
function runSeries(funcs, index, ctx, finalCb) {
if (index >= funcs.length) return finalCb && finalCb();
funcs[index](ctx.req, ctx.res, function() {
runSeries(funcs, index + 1, ctx, finalCb);
});
}
var funcs = [func1, func2, func3];
runSeries(funcs, 0, {req: null, res: null}, function() {
console.log('全部完成');
process.exit(0);
});
優點:扁平化、支援動態陣列、易於擴充中斷/重試邏輯。
async.series(推薦)const async = require('async');
async.series([
function(cb) { func1(null, null, cb); },
function(cb) { func2(null, null, cb); },
function(cb) { func3(null, null, cb); }
], function(err) {
if (err) console.error(err);
else console.log('全部完成');
process.exit(0);
});
Step 庫(較舊,風格類同)const Step = require('step');
Step(
function func1Step() { func1(null, null, this); },
function func2Step(err) { if (err) throw err; func2(null, null, this); },
function func3Step(err) { if (err) throw err; func3(null, null, this); },
function done(err) { if (err) throw err; console.log('完成'); process.exit(0); }
);
// 將回呼式函式 Promise 化
const promisify = fn => (...args) => new Promise((resolve, reject) =>
fn(...args, (err, result) => err ? reject(err) : resolve(result))
);
const p1 = promisify(func1);
const p2 = promisify(func2);
const p3 = promisify(func3);
async function run() {
try {
await p1(null, null);
await p2(null, null);
await p3(null, null);
console.log('全部完成');
} catch (e) {
console.error(e);
}
}
run();
async.parallel / Promise.all:並行執行,全部完成再繼續。async.parallelLimit / p-limit:限制併發數量。async.waterfall:前一個結果傳給下一個(管道流)。