-1
async function run(teamKey) {
  
  let { data } = await axios.get(URL);
  const { rounds } = data;
  let goals = 0;
  rounds.forEach((matchday) => {
    matchday.matches.forEach((match) => {
      if (match.team1.key == teamKey) {
        goals += match.score1;
      } else if (match.team2.key == teamKey) {
        goals += match.score2;
      }
    });
  });
  console.log("goals: ", goals); // I can see the goals in console log
  return goals;                  // but what's being returned is a pending promise
  
}

console.log("run(): ", run("arsenal"));

From what I can gather, the execution of run() completes and a pending promise is returned before axios.get() is resolved. From what I know about promises, there is only one way to get the goals and that is to chain a .then() after run(). Is there a way to get the run() function to return goals that can be used later in the code without making use of a chained .then()?

I tried everything, made another async function that called run() and returned the return value of run() but no luck.

dmp990
  • 1
  • Since `run` is an `async` function it will necessarily return a promise. That's what the `async` keyword does (that, and allowing you to use the `await` keyword). You either need to call `.then` on the promise, or put your code in an `async` function and `await` the promise. – Nicholas Tower Nov 30 '22 at 18:36

1 Answers1

0

As you have written async keyword at the start of run function so it means that this function will be async function and will return a promise, So to get data in console you have to handle the promise using then and catch statement when calling this function.

Like this:

run("arsenal")
    .then((response) => { console.log("run(): ", response) })
    .catch((error) => { console.log(error) })

Another approach to handle a promise is using await without then catch, all you need to do to call run function inside async function and then put await:

Like:

async function fetchData() {
    try {
        const response = await run("arsenal")
        console.log("run(): ", response)
    } catch (error) {
        console.log(error)
    }
}

fetchData()
Sheri
  • 1,383
  • 3
  • 10
  • 26