EN VI

Javascript - Response Data is undefined for async map function inside async function

2022-05-30 16:57:21

I am trying to fetch data from an API and modify the response from API but I am getting the modified response as undefined.

export const fetchData = async () => {
  
  const response = await fetch(`https://api/`, options);

  const results = await response.json();

  let responseData = await Promise.all(results.map(async (result) => {
    const response = await fetch(
      `https://another_api_endpoint/${result.id}`,
      options
    );

    const data = await response.json();

    result.newProperty = data.propertyTOAdd;

  }));

  console.log("Response Data:- ", responseData);

};

console.log()

Response Data:- [
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined,
  undefined, undefined
]

What am I doing wrong?

Solution:

you are not returning anything from map

try to change your code in this way

export const fetchData = async () => {
  
  const response = await fetch(`https://api/`, options);

  const results = await response.json();

  let responseData = await Promise.all(results.map(async (result) => {
    const response = await fetch(
      `https://another_api_endpoint/${result.id}`,
      options
    );

    const data = await response.json();

   return {...result, newProperty: data.propertyTOAdd};

  }));

  console.log("Response Data:- ", responseData);

};
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login