gpt4 book ai didi

javascript - JS 循环内的 fetch 中获取

转载 作者:行者123 更新时间:2023-12-02 21:27:12 31 4
gpt4 key购买 nike

问题是,如何摆脱调用第二个 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);
});

关于javascript - JS 循环内的 fetch 中获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60710423/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com