2016-12-19 7 views
4

async.waterfall()(またはtimed_waterfall())を上書きして、各ステップの実行時間を印刷したいとします。どうやってするか?非同期ウォーターフォール用のタイムドバージョン

async.waterfall([ 
    f=>{ 
     console.log('step1'); 
     f(); 
    }, 
    f=>{ 
     console.log('step2'); 
     f(); 
    }, 
    f=>{ 
     console.log('step3'); 
     f(); 
    }, 
], 
()=>{ 
    console.log('done'); 
}) 

所望の出力:async.jswaterfall()に対応

step1 
1ms 
step2 
2ms 
step3 
1ms 
done 
5ms 

答えて

1

function timed_waterfall(tasks, ender) { 
    function color(a) { 
     if (a == undefined) { return '\u001b(B\u001b[m' } 
     return '\u001b[38;5;'+a+'m' 
    } 

    var N = 0; 

    function go(args) { 
     function f() { 
      if (N>0)console.timeEnd(color(1)+' * '+N+color()) 
      var res = Array.prototype.slice.apply(arguments); 
      if (res[0]) { 
       ender.apply(null, res); 
      } 
      else { 
       res.splice(0, 1); 
       var cb = tasks.shift(); 
       if (cb) { 
        res.push(f); 
        console.time(color(1)+' * '+(++N)+color()) 
        cb.apply(null, res); 
       } 
       else { 
        res.unshift(null) 
        ender.apply(null, res); 
       } 
      } 
     } 
     f(null); 
    } 
    go([]); 
} 

それはトンにも合計を印刷するには、変更は簡単です。

1

これはいかがですか?

function timedWaterfall (tasks, callback) { 
 
    console.time('total') 
 
    async.waterfall(tasks.map(function (task, i) { 
 
    return function() { 
 
     if (i > 0) 
 
     console.timeEnd('step' + i) 
 
     console.time('step' + (i + 1)) 
 
     return task.apply(null, arguments) 
 
    } 
 
    }), 
 
    function() { 
 
    console.timeEnd('total') 
 
    callback.apply(null, arguments) 
 
    }) 
 
}

1

あなたは全くwaterfallを変更する必要はありません - 単にタスク(コールバック・撮影機能)にタイミングを追加ラッパー関数を記述します。

function withTiming(fn, name) { 
    if (typeof name == "number") name = "step"+name; 
    return function() { 
     var start = Date.now() 
     var lastIndex = arguments.length-1; 
     var cb = arguments[lastIndex]; 
     arguments[lastIndex] = function() { 
      console.log(name+": "+(start-Date.now())+"ms"); 
      cb.apply(this, arguments); 
     }; 
     return fn.apply(this, arguments); 
    }; 
} 

このようにasync.jsと一緒に使うことができます:

async.waterfall([ 
    f=>{ 
     console.log('step1'); 
     f(); 
    }, 
    f=>{ 
     console.log('step2'); 
     f(); 
    }, 
    f=>{ 
     console.log('step3'); 
     f(); 
    }, 
].map(withTiming),()=>{ 
//^^^^^^^^^^^^^^^ 
    console.log('done'); 
}) 
関連する問題