How to chain multiple fetch() promises?

前端 未结 7 1425
佛祖请我去吃肉
佛祖请我去吃肉 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:42

    If you want show only once "console.log("new", data)", you can check it with the index, like this:

    fetch(API_URL_DIARY)
        .then(response => response.json())
        .then(data => {
          console.log("old", data);
          return data;
        })
        .then(data => {
          data.forEach(function(e, index,array) {
            fetch(API_URL_FOOD_DETAILS + e.foodid)
            .then(response => response.json())
            .then(data => {
              array[index] = {...e, ...data};
              console.log("update");
               if ((data.length - 1) === index) { // CHECK INDEX HERE IF IS THE LAST
                 console.log("new", data)
               }
            })
          });
        });
    
    0 讨论(0)
提交回复
热议问题