How to chain multiple fetch() promises?

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

    You will need a recursive function to do this.

        fetch(API_URL_DIARY)
        .then(response => response.json())
        .then(data => {
          console.log("old", data);
          return data;
        })
        .then(data => {
    
        recursiveFetch(data)
    
        });
    
    function recursiveFetch(initialData){
            e = initialData[initialData.length-1]; //taking the last item in array
            fetch(API_URL_FOOD_DETAILS + e.foodid)
            .then(response => response.json())
            .then(data => {
              array[index] = {...e, ...data};
              console.log("update");
              initialData.pop() // removing last item from array, which is already processed
              if(initialData.length > 0)
                 recursiveFetch(initialData)
            })
    }
    

    Note: This is an untested code.

提交回复
热议问题