см. в консольку
function run(limit, func, params) {
'use strict';
if (typeof limit !== 'number' || limit < 1 || typeof func !== 'function' || !params || !params.length) {
return Promise.resolve([]);
}
return new Promise(function (resolve) {
var result = new Array(params.length);
var pos = 0;
var rcount = 0;
function ok(data) {
end(this, false, data);
}
function err(data) {
end(this, true, data);
}
function end(idx, error, data) {
result[idx] = {
data: error ? null : data,
error: error ? data : null
};
rcount++;
if (pos < params.length) {
Promise.resolve(func(params[pos])).then(ok.bind(pos), err.bind(pos));
++pos;
} else {
if (rcount >= params.length) {
resolve(result);
}
}
}
var m = Math.min(limit, params.length);
while (pos < m) {
Promise.resolve(func(params[pos])).then(ok.bind(pos), err.bind(pos));
++pos;
}
});
}
run(3, function(p) {
console.log('start: ', p);
return new Promise(function(r) { setTimeout(function(v) { console.log(v); r(v); }, p * 1000, 'result ' + p); });
}, [5, 3, 7, 2, 6]).then(console.log);