将其中一种异步方法重写为使用 promises 的方法
Rewrite one of the async methods into one that uses promises
如何将我的回调重写为使用 async 模块的承诺?例如,如果我有以下代码
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'
});
您会以某种方式使用几乎每个 promise 库中内置的 Promise.all
- 特别是在原生和 bluebird promises 中:
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]
});
Rewrite async.parallel
你不会为此使用任何回调函数,但你会为你想要 运行 的所有任务创建你自己的承诺。然后,您可以等待所有使用 Promise.all
:
的人
Promise.all([promiseMaker1(), promiseMaker2()]).then(callback);
Rewrite async.waterfall
为此,您将使用最原始的 promise 方法:.then()
。它用于链接承诺,将回调传递给承诺并为回调的结果获取新的承诺。但是请注意,promises 始终仅使用单个值来解析,因此您的 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'
});
如何将我的回调重写为使用 async 模块的承诺?例如,如果我有以下代码
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'
});
您会以某种方式使用几乎每个 promise 库中内置的 Promise.all
- 特别是在原生和 bluebird promises 中:
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]
});
Rewrite
async.parallel
你不会为此使用任何回调函数,但你会为你想要 运行 的所有任务创建你自己的承诺。然后,您可以等待所有使用 Promise.all
:
Promise.all([promiseMaker1(), promiseMaker2()]).then(callback);
Rewrite
async.waterfall
为此,您将使用最原始的 promise 方法:.then()
。它用于链接承诺,将回调传递给承诺并为回调的结果获取新的承诺。但是请注意,promises 始终仅使用单个值来解析,因此您的 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'
});