1

I want to return some data from an async function after an async forEach loop in javascript. How can I achieve that? I've tried this.

Method 1:
async function myFunc(myArray){
    sum = 0;
    myArray.forEach(async function (element, i){
       sum += element;
    });
    return sum;
}
it returns 0 always.

Method 2:
async function myFunc(myArray){
    sum = 0;
    myArray.forEach(async function (element, i){
       sum += element;

       if(i == myArray.length-1) return sum;
    });
}
it returns 0 too.

Can anyone help me, please?

1 Answers1

0

I'm not sure why you're using async functions here, but async functions return a promise (a promise that the data will be return at some time in the future), so you need to use the promise API to wait for that data to return. In your example there's no reason for your forEach callbacks to be async.

const myArray = [0, 1, 2, 3];

async function myFunc(myArray) {
  let sum = 0;
  myArray.forEach(element => sum += element);
  return sum;
}

myFunc(myArray).then(console.log);
Andy
  • 61,948
  • 13
  • 68
  • 95