node.jsのasyncモジュールのwaterfallの使い方

node.jsのasyncモジュールのwaterfallの使い方

nodeは7?からasync/awaitが使えるようになりましたが、asyncモジュールのwaterfallを使えば配列内にある無名関数を順次実行してくれます。また、最初の関数、次の関数へと結果を順次渡していってくれるので順次処理を行いたい場合は便利です。

waterfallの第一引数が配列、配列内に各無名関数を定義します。

waterfallの第二引数の関数はコールバック関数です。最終的な戻り値が返ってくる関数を定義します。

const async = require('async');  async.waterfall([   function(callback){     console.log("--first");     setTimeout(function() {       console.log('aaa --first');       callback(null, 'aaa'); // 引数が一つ     }, 100);   },   function(arg1, callback){     console.log("--second");     console.log("arg1:" + arg1);     setTimeout(function() {       console.log('bbb ccc --second');       callback(null, 'bbb', 'ccc');     }, 100);   },   function(arg1, arg2 , callback){     console.log("--third");     console.log("arg1:" + arg1);     console.log("arg2:" + arg2);     setTimeout(function() {       console.log('ddd eee --third');       callback(null, 'ddd', 'eee');     }, 100);   } ],   function(err, arg1, arg2) {     if(err) {       throw err;     }     console.log('result => ' + arg1, ':', arg2);
  }
);

以下、コンソールログです。

--first aaa --first --second arg1:aaa bbb ccc --second --third arg1:bbb arg2:ccc ddd eee --third result => ddd : eee

書く関数がコードが大きくなったり入れ子になる場合は、以下のように別で定義したほうが見やすいかもしれません。上記と同じです。(ログは省略しています)

const async = require('async');  function a(callback){   setTimeout(function() {     console.log('aaa --first');     callback(null, 'aaa'); // 引数が一つ   }, 0); }; function b(arg1, callback){   setTimeout(function() {     console.log('bbb ccc --second');     callback(null, 'bbb', 'ccc');   }, 0); }; function c(arg1, arg2 , callback){   setTimeout(function() {     console.log('ddd eee --third');     callback(null, 'ddd', 'eee');   }, 0); };  async.waterfall([a, b, c],   function(err, arg1, arg2) {     console.log(err);     if(err) {       throw err;     }     console.log('result => ' + arg1, ':', arg2);
  }
);

コメント

タイトルとURLをコピーしました