1

I have a function that is supposed to fetch from a recipes array that has a link of APIs to pull from.

for (let i = 0; i < recipes.length; i++) {
  console.log(recipes[i]);
  
  fetch(recipes[i]).then(response => {
    recipeData[recipes[i]] = response.json();
  }).catch(error => {
    console.log('Something went wrong fetching API');
  });
  console.log(recipeData[recipes[i]]);
}
console.log(recipeData.length)
if (recipeData.length == recipes.length) {
  resolve(true);
} else {
  reject('Could not fetch recipes');
}

I'm trying to save the response.json() into a dictionary, but it doesn't seem to be doing this because the recipeData dictionary is undefined. Why is this happening?

  • 2
    code _after_ the `fetch` will execute _before_ the callback function of `then()` is invoked. In other words, you are logging `recipeData[recipes[i]]` _before_ it is initialized inside the callback function of `then()` method. – Yousaf Oct 28 '21 at 05:21

0 Answers0