Vla*_*iuk 2 javascript for-loop fetch-api
问题是,我怎样才能摆脱调用 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);
});
};
Run Code Online (Sandbox Code Playgroud)
您可以使用 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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6314 次 |
| 最近记录: |