获取失败时如何停止foreach循环



我有一个函数:

function check(id) {
let index = 0
fetch('https://ddragon.leagueoflegends.com/api/versions.json')
.then(e => e.json())
.then((res) =>res.forEach( element =>{
fetch('https://ddragon.leagueoflegends.com/cdn/'+element+'/img/profileicon/'+id+'.png')
.then(response => {
if(response.ok){
index++
}
else{
return index
}
})
}))
}

代码似乎很脏,而且不正确,很抱歉。

我得到了一组数字,在第6行,我检查网站是否合法。在某个索引之后,将启动无效的URL。当一个无效的URL试图获取时,我想中断foreach循环。我试图将foreach循环转换为some循环,并尝试了一些try-catch块,但我无法打破循环。如果你想看看当无效的URL开始堆叠时它是如何堆叠的

如果您想统计满足/拒绝的请求数量,您可能会发现Promise.allSettled很有用。将端点添加到数组中,map在数组上创建一个promise数组,然后await解析/拒绝所有promise。然后,您可以检查结果以查看有多少请求的状态为"0";满足";或";拒绝";。

const arr = [
'https://jsonplaceholder.typicode.com/todos/1',
'https://jsonplaceholder.typicode.com/todos/2',
'https://madeup.url.com/todos',
'https://jsonplaceholder.typicode.com/todos/4',
'https://jsonplaceholder.typicode.com/todos/4'
];
// `map` over the array of endpoints and
// return an array of promises
function getPromises(arr) {
return arr.map(url => {
return fetch(url)
.then(res => {
if (res.ok) return res.json();
})
.catch(err => {
return Promise.reject('Request failed');
});
});
}
// Return the count of objects
// with a particular status
function count(data, status) {
return data.filter(obj => obj.status === status).length;
}
// Create an array of promises, `await` the result, and
// then find out how many were "fulfilled" or "rejected
async function main(arr) {
const promises = getPromises(arr);
const data = await Promise.allSettled(promises);
const fulfilled = count(data, 'fulfilled');
const rejected = count(data, 'rejected');
console.log(`Fulfilled: ${fulfilled}nRejected: ${rejected}`);
}
main(arr);

最新更新