将其中一个asynchronous方法重写为使用promise的方法

我怎样才能重写我的callback成承诺,使用asynchronous模块? 例如,如果我有以下代码

async.parallel([ function(){ ... }, function(){ ... } ], 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' }); 

重写async.parallel

你不会使用任何callback函数,但是你会为所有你想运行的任务创build你的promise。 那么,你可以等待所有使用Promise.all

 Promise.all([promiseMaker1(), promiseMaker2()]).then(callback); 

重写async.waterfall

为此,您将使用最原始的承诺方法: .then() 。 它用于链接承诺,将callback传递给承诺,并获得callback结果的新承诺。 但是请注意,承诺总是只用一个值来parsing,所以你的nodeback(null, 'one', 'two')例子将不起作用。 你将不得不使用一个数组或对象。

 Promise.resolve(['one', 'two']).then(function(args) { // args[0] now equals 'one' and args[1] now equals 'two' return Promise.resolve('three'); // you can (and usually do) return promises from callbacks }).then(function(arg1) { // arg1 now equals 'three' return 'done'; // but plain values also work }).then(function(result) { // result now equals 'done' }); 

你会使用Promise.all ,它几乎在每一个承诺库中都以这种或那种方式build立 – 特别是在本地和蓝鸟的承诺中:

 function fn1(){ return Promise.resolve(1); } function fn1(){ return Promise.resolve(2); } Promise.all([fn1(), fn2()]).then(function(results){ //access results in array console.log(results); // [1,2] });