我正在尝试使用 async 模块(v3),尤其是 async.mapLimit 方法来提交有限数量的并行异步请求。这与以下(简化的)示例代码中的回调配合使用效果很好:
async = require('async');
async.mapLimit(['1','2','3','4','5'], 3, function(num, callback){
setTimeout(function(){
num = num * 2,
console.log(num);
callback(null, num);
},
4000);
},function(err, results){
console.log(results);
});
结果我得到了单个值,最后得到了“结果”中包含所有值的数组:
[2,4,6,8,10]
现在我正在努力解决的是使用此方法的基于 Promise 的版本。文档 https://caolan.github.io/async/v3/docs.html#mapLimit说如果我不提供回调,它会返回一个 Promise。如何将这个基于回调的代码更改为使用 Promises?
我尝试过例如这个,但它只显示第一组请求(这是在评论中的第一个建议之后更新的):
let numPromise = async.mapLimit(['1','2','3','4','5'], 3, function(num, callback){
setTimeout(function(){
num = num * 2,
console.log(num);
callback(null, num);
},
4000);
});
Promise.all([numPromise]) //always calls .then immediately, without result
.then((result) => console.log("success:" + result))
.catch(() => console.log("no success"));
我确实正确地返回了所有单个值,但是“.then”立即执行并为我提供了“成功”和一个空的“结果”变量。
注:我看过这个帖子ES6 Promise 替换 async.eachLimit / async.mapLimit https://stackoverflow.com/questions/43892296/es6-promise-replacement-of-async-eachlimit-async-maplimit当然,但我认为这不能回答我的问题。
PS:我已经找到了这个问题的其他解决方案,但我真的对如何正确使用这个模块(使用简短、干净的代码)感兴趣。