0

I need to push to an array located to uppser scope of forEach loop. In each it calls a promise with a value, and pushes the result to the array.

function getSquareOfEvenNumber(num) {
  return new Promise((resolve, reject) =>{
    if (num % 2 !== 0 ) reject('Please pass a even number only!');
    resolve(num * num);
    })
}

const  getResult = (a) => {
  let resultants = [6];
  let totalErrors = 0;
  a.forEach(async (e) => {  
    try {
      const d = await getSquareOfEvenNumber(e)
      resultants.push(d)
    } catch(err) {
      totalErrors++;
    }
  })
  return {
    resultants,
    totalErrors,
    resultantCount: resultants.length
  };
}

Also, I have tried below.

a.forEach(async (e) => {  
    getSquareOfEvenNumber(e)
      .then((d) => resultants.push(d))
      .catch((err) => resultants++)
  })

Also, tried with for...of loop.

 for (e of a) {  
    getSquareOfEvenNumber(e)
      .then((d) => resultants.push(d))
      .catch((err) => resultants++)
  }
But 

it's also not working, I am getting the initial values of the upper variables. They are not being modified in the loop.

{ resultants: [ 6 ], totalErrors: 0, resultantCount: 1 }

Please someone explain why this is happening and if there is any workaround.

SharpBlade
  • 47
  • 8
  • Regarding your update, you need to `await` inside `for..of` like this: https://jsfiddle.net/adigas/e620b15z/ Please check the duplicate for more details – adiga Sep 02 '20 at 05:11
  • @adiga why using `promise().then()` doesn't work inside `for of`? In link will be helpful thanks. – SharpBlade Sep 02 '20 at 05:13
  • 1
    If you don't use `await` inside `for...of` the loop will iterate over the data synchronously. `await` is responsible for "suspending" execution until the promise is resolved. – Felix Kling Sep 02 '20 at 05:35
  • The callback inside `.then((d) => resultants.push(d))` runs at a later point of time after the `for..of` is completed. You need to use `await` on the promise returned by `getSquareOfEvenNumber` to *stop* the `for..of` from proceeding further. You can add a `debugger;` inside the method and check the order of execution. – adiga Sep 02 '20 at 06:47

0 Answers0