Skip to content

Instantly share code, notes, and snippets.

@tomaszgil

tomaszgil/asyncForEach.js

Last active May 12, 2021
Embed
What would you like to do?
const startTimestamp = getMiliseconds();
function getMiliseconds() {
return new Date(Date.now()).getMilliseconds();
}
function getMillisecondsElapsed() {
return getMiliseconds() - startTimestamp;
}
function wait(timeout = 0) {
return new Promise((resolve) => setTimeout(resolve, timeout));
}
const tasks = [
() => wait(100).then(() => console.log("Task 1 finished at", getMillisecondsElapsed())),
() => wait(100).then(() => console.log("Task 2 finished at", getMillisecondsElapsed())),
() => wait(100).then(() => console.log("Task 3 finished at", getMillisecondsElapsed())),
];
async function run(tasks = []) {
for (const task of tasks) {
await task();
}
console.log("All tasks finished at", getMillisecondsElapsed());
}
function runForEach(tasks = []) {
tasks.forEach(async (task) => {
await wait(100);
await task();
});
console.log("All tasks finished at", getMillisecondsElapsed());
}
function runLongerForEach(tasks = []) {
tasks.forEach(async (task) => {
await wait(100);
await task();
});
console.log("All tasks finished at", getMillisecondsElapsed());
}
function forEach() {
Array.prototype.forEach = function (callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
}
function patchForEach() {
Array.prototype.forEach = async function (callback) {
for (let i = 0; i < this.length; i++) {
await callback(this[i], i, this);
}
};
}
async function runAsyncForEach(tasks = []) {
patchForEach();
await tasks.forEach(async (task) => {
await task();
});
console.log("All tasks finished at", getMillisecondsElapsed());
}
run(tasks);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment