0

I'm just curious about this..

  1. Why forEach and for...of are not working as same with async function

  2. What if you didn't know that "forEach is not working as expected with async function",
    how to know this in advance?

  3. 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()
RayKim
  • 423
  • 1
  • 6
  • 22
  • `forEach` was introduced to JavaScript a long time ago, well before async functions existed, so it has no concept of an async loop. – Keith Dec 01 '20 at 02:25
  • @Keith Thanks. It is pretty understandable answer. – RayKim Dec 01 '20 at 04:23

0 Answers0