萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Node.js 實現同步流程控制的三種模式:回呼地獄、遞迴、Async 庫

問題場景

三個非同步函式 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);
});

優點:扁平化、支援動態陣列、易於擴充中斷/重試邏輯。

方案三:使用成熟流程控制庫

3.1 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);
});

3.2 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 + async/await

// 將回呼式函式 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:前一個結果傳給下一個(管道流)。
copyright © 萬盛學電腦網 all rights reserved