小编Use*_*ame的帖子

如何链接多个 fetch() 承诺?

以下代码获取一个 json 列表,然后为每个列表项执行另一个获取调用以更改它们的值。问题是它不是同步完成的。“new”在“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)
});
Run Code Online (Sandbox Code Playgroud)

更新

以下是我如何合并@Andy 的解决方案:

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 () => …
Run Code Online (Sandbox Code Playgroud)

javascript fetch-api

3
推荐指数
1
解决办法
9936
查看次数

标签 统计

fetch-api ×1

javascript ×1