I'm trying to use the async module (v3) and especially the async.mapLimit method to submit a limited number of parallel asnychronous requests. This works well with callbacks in the following (simplified) sample code:
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);
});
As result I get the single values and finally the array with all values in 'results':
[2,4,6,8,10]
Now what I'm struggling with is to use the Promise based version of this method. The documentation says it returns a Promise if I don't supply a callback. How can I change this callback-based code into using Promises?
I tried e.g. this, but it only shows the first set of requests (this is updated after the first suggestions in the comments):
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"));
I do get back all single values correctly, but the '.then' executes immediately and gives me 'Success' with an empty 'result' variable.
Note: I have seen this thread ES6 Promise replacement of async.eachLimit / async.mapLimit of course, but I don't think that answers my question.
PS: I have found other solutions to this problem already, but I am really interested in how to use this module properly (with short, clean code).