gpt4 book ai didi

Javascript fetch() 故障转移 URL

转载 作者:行者123 更新时间:2023-11-30 09:13:53 25 4
gpt4 key购买 nike

我有一个 URL 数组,我想对其执行 fetch() 请求:

const urls = [
'https://dewnuf111111.com/configuration',
'https://dewnuf222222.com/configuration',
'https://bcsmania.co.uk/test.json'
];

如果抓取发现错误(例如站点不存在、内部错误等),我希望它尝试下一个 URL,所以我添加了一个增量器。一旦它到达一个工作 URL 并成功发出请求,它应该简单地 console.log('DONE'),但我似乎无法让它工作。

这是我到目前为止编写的代码:

const urls = [
'https://dewnuf111111.com/configuration',
'https://dewnuf222222.com/configuration',
'https://bcsmania.co.uk/test.json'
];

let obj = {a: 'test'};
let counter = 0;

function ajax(url) {
// Check for for last URL in the array
if (counter < urls.length) {
return fetch(url)
.then(response => {
// Combine objects
obj = Object.assign(obj, response.json());
console.log(urls[counter], obj);
return Promise.resolve(obj);
}).catch(error => {
counter++;
// Fetch next URL
ajax(urls[counter]);
});
}
}

function getConfigurations() {
return ajax(urls[counter]);
}

getConfigurations().then((configurations) => {
console.log('DONE', configurations);
});

这是一个JSFiddle查看预览。

任何人都可以阐明我可能哪里出错了吗?我是否需要使函数 async 然后 await 结果?

最佳答案

您需要在 catch 中返回 Promise,以便也能够从中链接:

.catch(error => {
counter++;
// return Fetch next URL
return ajax(urls[counter]);
});

关于Javascript fetch() 故障转移 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528853/

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