Skip to content

Instantly share code, notes, and snippets.

@nsisodiya
Created June 14, 2019 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nsisodiya/54e2847f8cef1371b8ac227d27a867cd to your computer and use it in GitHub Desktop.
Save nsisodiya/54e2847f8cef1371b8ac227d27a867cd to your computer and use it in GitHub Desktop.
The best Way to run multiple async functions parallel and sequential using Array Async Map
var getTime = (function() {
var startTime = Date.now();
return function() {
return (Date.now() - startTime) / 1000;
};
})();
Array.prototype.asyncMapP = function(callback) {
return Promise.all(this.map(callback));
};
Array.prototype.asyncMapS = async function(callback) {
var res = [];
for (var i = 0; i < this.length; i++) {
res.push(await callback(this[i], i, this));
}
return res;
};
function getSquare(i, j, arr) {
console.log(`executing getSquare at ${getTime()}`);
return i * i;
}
function getSquareAsync(i, j, arr) {
return new Promise(resolve =>
setTimeout(() => {
console.log(`executing getSquareAsync at ${getTime()}`);
resolve(i * i);
}, 2000)
);
}
async function run() {
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var result1 = arr.map(getSquare);
console.log(`result1 @ ${getTime()}`, result1);
// result1 is [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
var result2 = await arr.asyncMapP(getSquareAsync);
console.log(`result2 @ ${getTime()}`, result2);
// result2 is [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
var result3 = await arr.asyncMapS(getSquareAsync);
console.log(`result3 @ ${getTime()}`, result3);
// result3 is [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
}
run();
executing getSquare at 0.001
executing getSquare at 0.013
executing getSquare at 0.013
executing getSquare at 0.013
executing getSquare at 0.013
executing getSquare at 0.013
executing getSquare at 0.013
executing getSquare at 0.013
executing getSquare at 0.013
executing getSquare at 0.013
result1 @ 0.013 [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
executing getSquareAsync at 2.021
executing getSquareAsync at 2.021
executing getSquareAsync at 2.022
executing getSquareAsync at 2.022
executing getSquareAsync at 2.022
executing getSquareAsync at 2.022
executing getSquareAsync at 2.022
executing getSquareAsync at 2.022
executing getSquareAsync at 2.022
executing getSquareAsync at 2.022
result2 @ 2.022 [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
executing getSquareAsync at 4.028
executing getSquareAsync at 6.03
executing getSquareAsync at 8.032
executing getSquareAsync at 10.034
executing getSquareAsync at 12.036
executing getSquareAsync at 14.04
executing getSquareAsync at 16.046
executing getSquareAsync at 18.049
executing getSquareAsync at 20.053
executing getSquareAsync at 22.053
result3 @ 22.054 [ 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