I'm just curious about this..
Why forEach and for...of are not working as same with async function
What if you didn't know that "forEach is not working as expected with async function",
how to know this in advance?Or is there a code for
Array.prototype.forEach
that i can read like github source?
I made this example for question
// time array
tempArray = [{index:1, time:1500 }, {index:2, time:500}, {index:3, time:3000}];
// async forEach function
async function asyncForEach () {
tempArray.forEach( async item => {
try {
const item = await awaitFunc(item);
console.log(`[asyncForEach] index:${item.index}, time:${item.time}`);
} catch(e) {
console.error('[asyncForEach] error : ', e);
}
})
}
// async for...of function
async function asyncForOf () {
for (const file of tempArray) {
try {
const item = await awaitFunc(file);
console.log(`[asyncForOf] index:${item.index}, time:${item.time}`);
} catch(e) {
console.error('[asyncForOf] error :', e);
}
}
}
// base promise function
function awaitFunc( item ) {
return new Promise( (resolve, reject) => {
setTimeout( () => {
resolve(item);
console.log(`[inside/awaitFunc] index:${item.index}, time:${item.time}`);
}, item.time)
});
}
// Uncomment which code you'd like to test
//asyncForEach()
//asyncForOf()