title: How to chain multiple fetch() promises?
body: <p>The following code fetches a json list and then does another fetch call for each list item to change their values. The problem is that it’s not done synchronously. “new” is printed to the console before “update”. </p>
  
  <pre><code>fetch(API_URL_DIARY)
  .then(response =&gt; response.json())
  .then(data =&gt; {
    console.log("old", data);
    return data;
  })
  .then(data =&gt; {
    data.forEach(function(e, index,array) {
      fetch(API_URL_FOOD_DETAILS + e.foodid)
      .then(response =&gt; response.json())
      .then(data =&gt; {
        array[index] = {...e, ...data};
        console.log("update");
      })
    });
  
    console.log("new", data)
  });
  </code></pre>
  
  <p><strong>Update</strong></p>
  
  <p>Here's how I incorporated @Andy's solution:</p>
  
  <pre><code>function fetchFoodDetails(id, index) {
    return fetch(API_URL_FOOD_DETAILS + id)
    .then(response =&gt; response.json())
    .then(data =&gt; {
        return [index, data];
    });
  }
  
  function fetchDiary() {
    return fetch(API_URL_DIARY)
    .then(response =&gt; response.json())
    .then(data =&gt; {
      return data;
    })
  }
  
  (async () =&gt; {
    const data = await fetchDiary();
    console.log("old", JSON.stringify(data));
  
    const promises = data.map((food, index) =&gt; fetchFoodDetails(food.id, index));
    await Promise.all(promises).then(responses =&gt; {
      responses.map(response =&gt; {
        data[response[0]] = {...data[response[0]], ...response[1]};
        console.log("update");
      })
    });
    console.log('new', JSON.stringify(data));
  })();
  </code></pre>
  
  <p>It was more difficult so I went with @connoraworden's solution. But I think it can be simplified.</p>
  
  <p>Thanks for all your answers.</p>