Last active
August 30, 2024 13:03
-
-
Save atinux/fd2bcce63e44a7d3addddc166ce93fb2 to your computer and use it in GitHub Desktop.
JavaScript: async/await with forEach()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const waitFor = (ms) => new Promise(r => setTimeout(r, ms)) | |
const asyncForEach = async (array, callback) => { | |
for (let index = 0; index < array.length; index++) { | |
await callback(array[index], index, array) | |
} | |
} | |
const start = async () => { | |
await asyncForEach([1, 2, 3], async (num) => { | |
await waitFor(50) | |
console.log(num) | |
}) | |
console.log('Done') | |
} | |
start() |
German-Stepanov
commented
Apr 12, 2021
I don´t get why callback reicive 3 arguments, in the start function the call of asyncForEach method the second parameter is callback and is just sending one argument ... can some explain step by step?
Here's my typescript version (Basically @wodCZ's codeblock) with the ability to return data which is readable in the form of an array
async function asyncForEach<T = any>(array: T[], callback: (value: T, index?: number, array?: T[]) => any): Promise<any[]> {
const data: any[] = [];
for (let index = 0; index < array.length; index++) {
await (async () => {
const item = await callback(array[index], index, array);
if (item !== undefined) data.push(item);
return;
})();
}
return Promise.resolve(data);
}
I feel like this is just a glorified promise.all at this point.
Why not use for await()
?
const waitFor = (ms) => new Promise(r => setTimeout(r, ms))
const start = async () => {
for await (num of [1, 2, 3]) {
await waitFor(50)
console.log(num)
};
console.log('Done')
}
start()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment