寫 nodejs 就會用到非同步的 callback
就會碰到所謂的「callback hell」的囧境
什麼是 callback hell? 如下所示:
doSomeAsyncFunc(function () { doSomeAsyncFunc(function () { doSomeAsyncFunc(function () { doSomeAsyncFunc(function () { doSomeAsyncFunc(function () { doSomeAsyncFunc(function () { doSomeAsyncFunc(function () { doSomeAsyncFunc(function () { doSomeAsyncFunc(function () { // 我到底在第幾層地獄啊!? }) }) }) }) }) }) }) })
這樣光要看懂就很辛苦了,還要怎麼維護程式碼呢?
有幾種解決方式:
- async.waterfall
- promise
- async/await
先來看看 async.waterfall 如何解決問題
步驟如下:
1. 先安裝 async package : $ npm install --save async
2. import async package : var async = require("async");
3. waterfall(tasks, callback) 的說明:
Runs the tasks array of functions in series, each passing their results to the next in the array. However, if any of the tasks pass an error to their own callback, the next function is not executed, and the main callback is immediately called with the error.簡單來說,只要 error 的參數是 null ,就會一直往下丟 callback,
若中途呼叫 callback 且 error 參數不為 null ,則直接進入 mail callback
範例:
async.waterfall([ function(callback) { callback(null, 'one', 'two'); }, function(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); }, function(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); } ], function (err, result) { // result now equals 'done' });
也就是說,一開始的 callback hell sample 可以改成:
async.waterfall([ function(callback) { doSomeAsyncFunc1(function (error, result) { callback(error, result); }); }, function(callback) { doSomeAsyncFunc2(function (error, result) { callback(error, result); }); }, function(callback) { doSomeAsyncFunc3(function (error, result) { callback(error, result); }); } ...... ], function (err, result) { // main callback if (err) { // do something } else if { // do something } });
這樣就可以攤平可怕的 callback hell,回到地球表面囉!
reference: https://caolan.github.io/async/docs.html#waterfall
沒有留言:
張貼留言