Async code - returning a value from inside Promise.all

Hello,

Here is my solution to a code challenge.

I can see it’s working. I thought I was almost done when I saw the console.log was what I expected. The only step left was making the getNumDraws function to actually return numOfDrawnMatchesInYear. Oh boy… :weary:

Note: the exercise gives the function with the async keyword (commented out). I don’t even know if I could delete it regarding that it was given from the beginning. So if possible, consider that async keyword exists and can’t be removed.

Maybe that hides a hint to the solution I can’t figure out.

I thought Promise.all() would give me the keys to the async heaven after reading this article:

https://codeburst.io/javascript-making-asynchronous-calls-inside-a-loop-and-pause-block-loop-execution-1cb713fbdf2d

Would you have used another approach? How would you get the getNumDraws function return the value that it shows in the console.log?

Any help or feedback will be more than welcome. Thanks in advance! :pray: :love_you_gesture:

PS: Not too satisfied with declaring loadMultipleDrawRequests and invoking it right away. Does it look right to you? :face_with_raised_eyebrow:

CODE UPDATED AFTER SOME FEEDBACK, READ COMMENT BELOW TO SEE THE OUTPUT

async function getNumDraws(year) {
  function fetchData(numGoals) {
    return new Promise((resolve, reject) => {
      fetch(
        `https://jsonmock.hackerrank.com/api/football_matches?year=${year}&team1goals=${numGoals}&team2goals=${numGoals}&page=1`
      )
        .then((res) => res.json())
        .then((data) => resolve(data.total))
        .catch((err) => console.log(err));
    });
  }

  function loadMultipleDrawRequests() {
    const possibleNumOfGoalsScoredByTeam = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const numOfDrawRequests = [];

    possibleNumOfGoalsScoredByTeam.forEach((goalsByTeam) => {
      numOfDrawRequests.push(fetchData(goalsByTeam));
    });

    return Promise.all(numOfDrawRequests).then((allDrawData) => {
      const numOfDrawnMatchesInYear = allDrawData.reduce(
        (acc, currVal) => acc + currVal
      );
      return numOfDrawnMatchesInYear;
    });
  }

  let innerFunctionReturnVal = await loadMultipleDrawRequests();
  console.log("value displayed:", innerFunctionReturnVal);
  return innerFunctionReturnVal;    // **I want to return an int (value displayed), NOT a promise**    
}

getNumDraws(2011);

If I understand the issue correctly, the expected result is calculated correctly somewhere, but it’s not returned where it should? Consider then what is returned by the getNumDraws function and by the inner loadMultipleDrawRequests function.

1 Like

Thanks!

I considered that and tried to simplify the problem to the core issue, which: I want the returned value to be an int (check the log), NOT a promise.

Here is the code after some changes:

async function getNumDraws(year) {
  function fetchData(numGoals) {
    return new Promise((resolve, reject) => {
      fetch(
        `https://jsonmock.hackerrank.com/api/football_matches?year=${year}&team1goals=${numGoals}&team2goals=${numGoals}&page=1`
      )
        .then((res) => res.json())
        .then((data) => resolve(data.total))
        .catch((err) => console.log(err));
    });
  }

  function loadMultipleDrawRequests() {
    const possibleNumOfGoalsScoredByTeam = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const numOfDrawRequests = [];

    possibleNumOfGoalsScoredByTeam.forEach((goalsByTeam) => {
      numOfDrawRequests.push(fetchData(goalsByTeam));
    });

    return Promise.all(numOfDrawRequests).then((allDrawData) => {
      const numOfDrawnMatchesInYear = allDrawData.reduce(
        (acc, currVal) => acc + currVal
      );
      return numOfDrawnMatchesInYear;
    });
  }

  let innerFunctionReturnVal = await loadMultipleDrawRequests();
  console.log("value displayed:", innerFunctionReturnVal);
  return innerFunctionReturnVal;    // **I want to return an int (value displayed), NOT a promise**    
}

getNumDraws(2011);

And here is the output:

image

I hope the question is more clear now.

Looking forward to reading your comments! Thanks in advance!!

Now that getNumDraws is async function it will return promise until it’s fulfilled, so it’s needed to wait for that moment as well.

1 Like