如何将我的回调重写为使用 async 的 promise 模块?例如,如果我有以下代码
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'
});
最佳答案
Rewrite
async.parallel
您不会为此使用任何回调函数,但您可以为要运行的所有任务创建自己的 promise 。然后,您可以使用 Promise.all
等待所有这些。 :
Promise.all([promiseMaker1(), promiseMaker2()]).then(callback);
Rewrite
async.waterfall
为此,您可以使用最原始的 Promise 方法:.then()
。它用于链接 Promise、将回调传递给 Promise 并为回调结果获取新的 Promise。但请注意,promise 始终仅使用单个值进行解析,因此您的 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'
});
关于javascript - 将异步方法之一重写为使用 Promise 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449777/