在循环 JS 中获取获取

Fetch in fetch inside a loop JS

问题是,我怎样才能避免调用 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);            
    }); 
};

你可以使用 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.all() 等待所有这些请求完成。然后当所有的请求都完成后,使用另一个 Promise.all() 里面有一个 map() 到 return 每个请求的 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);            
  });