如何链接多个fetch()承诺? [英] How to chain multiple fetch() promises?

查看:61
本文介绍了如何链接多个fetch()承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码获取一个json列表,然后对每个列表项进行另一个访存调用以更改其值.问题是它没有同步完成.在更新"之前,将新"打印到控制台.

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".

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");
    })
  });

  console.log("new", data)
});

更新

这是我合并@Andy解决方案的方式:

Here's how I incorporated @Andy's solution:

function fetchFoodDetails(id, index) {
  return fetch(API_URL_FOOD_DETAILS + id)
  .then(response => response.json())
  .then(data => {
      return [index, data];
  });
}

function fetchDiary() {
  return fetch(API_URL_DIARY)
  .then(response => response.json())
  .then(data => {
    return data;
  })
}

(async () => {
  const data = await fetchDiary();
  console.log("old", JSON.stringify(data));

  const promises = data.map((food, index) => fetchFoodDetails(food.id, index));
  await Promise.all(promises).then(responses => {
    responses.map(response => {
      data[response[0]] = {...data[response[0]], ...response[1]};
      console.log("update");
    })
  });
  console.log('new', JSON.stringify(data));
})();

要困难得多,所以我选择了@connoraworden的解决方案.但我认为可以简化.

It was more difficult so I went with @connoraworden's solution. But I think it can be simplified.

感谢您的回答.

推荐答案

最好的方法是使用Promise.all()map().

在这种情况下,什么地图将返回fetch的所有承诺.

What map will do in this context return all the promises from fetch.

然后将发生的事情是await,它将使您的代码同步执行,因为它将在继续执行之前等待所有诺言得到解决.

Then what will happen is await will make your code execution synchronous as it'll wait for all of the promise to be resolved before continuing to execute.

在这里使用forEach的问题在于,它不等待异步请求完成才移到下一个项目.

The problem with using forEach here is that it doesn't wait for asynchronous request to be completed before it moves onto the next item.

您应该在此处使用的代码是:

The code that you should be using here is:

fetch(API_URL_DIARY)
    .then(response => response.json())
    .then(data => {
        console.log("old", data);
        return data;
    })
    .then(async data => {
        await Promise.all(data.map((e, index, array) => {
            return fetch(API_URL_FOOD_DETAILS + e.foodid)
                .then(response => response.json())
                .then(data => {
                    array[index] = {...e, ...data};
                    console.log("update");
                })
        }));

        console.log("new", data)
    });

这篇关于如何链接多个fetch()承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆