Search code examples
javascriptreactjsfetchundefinedpromise.all

fetch result from API returns undefined


I am trying to fetch data from an API but keep getting undefined as result. I am using promise.all to chain API calls, and then chaining promises to do other operations on data. I seem to be unable to get my results to be passed to state.

Here's the offending code:

if (gameDifficulty === "mixed") {
  const result = await Promise.all([
    fetchClient.getData(
      getEndpoint(
        `amount=${countValues[0]}&difficulty=easy&type=${questionType}`
      )
    ),
    fetchClient.getData(
      getEndpoint(
        `amount=${countValues[1]}&difficulty=medium&type=${questionType}`
      )
    ),
    fetchClient.getData(
      getEndpoint(
        `amount=${countValues[2]}&difficulty=hard&type=${questionType}`
      )
    ),
  ])
    .then(function (responses) {
      console.log(responses);
      console.log(result); //returns undefined
      return Promise.all(
        responses.map(function (response, idx) {
          return fetchClient.processData(response, "results");
        })
      );
    })
    .then(function (data) {
      console.log(data);

      console.log(result); // returns undefined
      return [...data[0], ...data[1], ...data[2]];
    });
}

Solution

  • Make it simple with async/await syntax.

    Avoid mixing async/await with then/catch style.

    const getDataResponses = await Promise.all([
      fetchClient.getData(
        getEndpoint(
          `amount=${countValues[0]}&difficulty=easy&type=${questionType}`
        )
      ),
      fetchClient.getData(
        getEndpoint(
          `amount=${countValues[1]}&difficulty=medium&type=${questionType}`
        )
      ),
      fetchClient.getData(
        getEndpoint(
          `amount=${countValues[2]}&difficulty=hard&type=${questionType}`
        )
      ),
    ]);
    
    const data = await Promise.all(
      getDataResponse.map((response) => {
        return fetchClient.processData(response, "results");
      })
    );
    
    console.log('getDataResponses', getDataResponses);
    console.log('processDataResponse', data);
    return [...data[0], ...data[1], ...data[2]];