How to chain multiple fetch() promises?

前端 未结 7 1434
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 17:08

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

7条回答
  •  天涯浪人
    2021-01-06 17:36

    fetch is a Promise. This is asyncronous call, so the "new" console.log runs before finished all the promises. Use Promise.all() for that.

    You can do this so:

    fetch(API_URL_DIARY)
      .then(response => response.json())
      .then(data => {
        console.log("old", data);
        return data;
      })
      .then(data => {
        return Promise.all(data.map(food =>
          fetch(API_URL_FOOD_DETAILS + food.foodid)
            .then(resp => resp.json())
            .then(json => {
              // do some work with json
              return json
            })
        ))
      })
      .then(data => console.log('new', data))
    

提交回复
热议问题