【问题标题】:Fetch in fetch inside a loop JS在循环JS中获取
【发布时间】:2020-06-27 19:52:45
【问题描述】:

问题是,我怎样才能摆脱调用 second fetch 300 次?还是有其他方法可以做到这一点,我在做什么? 此外,如何对第一个 api 进行有序(不想排序)调用,因为它们以混乱的异步方式来自 api?

for(let i=1;i<=300; i++) {
  fetch(`example.api/incomes/${i}`)   // should be returned 300 times
    .then(response => {
      if(response.ok) return response.json();
      throw new Error(response.statusText);
    })
    .then(function handleData(data) {
        return fetch('example.api')   // should be returned 1 time
        .then(response => {
            if(response.ok) return response.json();
            throw new Error(response.statusText);
          })
    })
    .catch(function handleError(error) {
        console.log("Error" +error);            
    }); 
};

【问题讨论】:

  • 所以你想调用第一个fetch 300 次,然后在所有提取完成后调用第二个?
  • 如果您可以控制 API,我建议您实现某种批处理机制。 300 次 API 调用只会减慢您正在执行的操作,并使您的 API 服务器过载。
  • 是的,他们应该有权检索彼此的数据。第一次提取是 300 个对象,应该绑定对应于第二次提取数组中项目的 ID。
  • @MaazSyedAdeeb its like same API, but each item lays down under different api adress. So im 使用 {i} 参数来访问它。

标签: javascript for-loop fetch-api


【解决方案1】:

你可以使用 Promise all 来解决它。

let promises = [];
for (let i = 1; i <= 300; i++) {
  promises.push(fetch(`example.api/incomes/${i}`));
}
Promise.all(promises)
  .then(function handleData(data) {
    return fetch("example.api") // should be returned 1 time
      .then(response => {
        if (response.ok) return response.json();
        throw new Error(response.statusText);
      });
  })
  .catch(function handleError(error) {
    console.log("Error" + error);
  });

【讨论】:

  • 我想用Promise 获取我的GH repos api.github.com/users/tik9/repos,然后获取另一个api 以将ISO 日期更改为另一种日期格式。但是Promise 不起作用,我得到TypeError: response.json is not a functionpromises =[];promises.push(fetch(github));Promise.all(promises).then((response) =&gt; response.json())
  • Promise.all 将返回响应数组,您需要循环。 Promise.all(promises).then((responses) =&gt; responses.map(r =&gt; .json()))
【解决方案2】:

将所有请求存储在一个数组中。然后使用Promise.all() 等待所有这些请求完成。然后,当所有请求都完成后,使用另一个 Promise.all()map() 来返回每个请求的 JSON 并等待所有请求完成。

现在您的data 参数将在下一个then 回调中包含一组可用的对象。

function fetch300Times() {
  let responses = [];
  for(let i = 1; i <= 300; i++) {.
    let response = fetch(`example.api/incomes/${i}`);
    responses.push(response);
  } 
  return Promise.all(responses);
}

const awaitJson = (response) => Promise.all(responses.map(response => {
  if(response.ok) return response.json();
  throw new Error(response.statusText);
}));

fetch300Times()
  .then(awaitJson)
  .then(data => {
    fetch('example.api')   // should be returned 1 time
      .then(response => {
        if(response.ok) return response.json();
        throw new Error(response.statusText);
      });
  }).catch(function handleError(error) {
    console.log("Error" +error);            
  });  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2015-06-12
    • 2011-03-10
    • 2021-08-12
    • 2021-07-19
    • 2021-12-21
    相关资源
    最近更新 更多