Skip to content

Instantly share code, notes, and snippets.

@nsisodiya
Created June 17, 2019 20:03
Show Gist options
  • Save nsisodiya/b58c2f9ae1dfc651fba9ae1f5fff3778 to your computer and use it in GitHub Desktop.
Save nsisodiya/b58c2f9ae1dfc651fba9ae1f5fff3778 to your computer and use it in GitHub Desktop.
Array.prototype.asyncMapPool = async function(n, t) {
var r = [],
i = this.map(() => !1),
o = this.length,
e = this;
return new Promise(function(a, s) {
function f() {
if (h < o) {
var t = h;
r.push(
n(e[h], h, e).then(function(n) {
return (
(i[t] = !0),
0 === i.filter(n => !1 === n).length && a(Promise.all(r)),
f(),
n
);
})
);
}
h++;
}
for (var h = 0; h < t; ) f();
});
};
function getSquareAsync(v, i, arr) {
return new Promise(resolve =>
setTimeout(() => {
console.log(`executing getSquareAsync at ${getTime()}, ${v}, ${i}`);
resolve(v * v);
}, 2000)
);
}
async function run() {
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var result2 = await arr.asyncMapPool(getSquareAsync, 3);
console.log(`result2 @ ${getTime()}`, result2);
}
run();
executing getSquareAsync at 2.021, 1, 0
executing getSquareAsync at 2.022, 2, 1
executing getSquareAsync at 2.022, 3, 2
executing getSquareAsync at 4.025, 4, 3
executing getSquareAsync at 4.025, 5, 4
executing getSquareAsync at 4.025, 6, 5
executing getSquareAsync at 6.026, 7, 6
executing getSquareAsync at 6.026, 8, 7
executing getSquareAsync at 6.026, 9, 8
executing getSquareAsync at 8.028, 10, 9
result2 @ 8.029 [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment