如何解决如果执行了.catch on promise,如何发出第二个请求?
如果执行了.catch on promise,我如何发出第二个请求,以便成功获取数据
因为如果执行了.catch,我没有收到数据。而且我必须再次刷新页面才能获取数据。
fetch("https://randomuser.me/api")
.then(result => result.json())
.then(data => {
console.log(data)
})
.catch(error => console.log(error))
解决方法
您只想重试捕获?您将需要再次调用发出请求的函数。这称为递归。即:
function makeRequest() {
fetch("https://randomuser.me/api")
.then((result) => result.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
return makeRequest(); // Calls itself recursively
});
}
但是,这引入了无限循环的可能性,因此您需要一些突破的方法,也许像这样:
function makeRequest(attempt=0) {
const maxRetries = 3;
if (attempt > maxRetries) {
throw new Error(`Could not fetch user after ${attempt} attempts`);
}
fetch("https://randomuser.me/api")
.then((result) => result.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
// Call self and increment the attempt number.
// Very important to ensure that the break condition
// can be met or we can end up calling the function
// forever with no way to escape. This is called an
// infinite loop.
return makeRequest(attempt + 1);
});
}
您还可以使重试的逻辑更为复杂,例如,如果attempt
为gt 0,则在下一个请求之前引入超时,添加指数补偿等。
始终记住在使用递归函数时要注意无限循环。
,您可以将fetch
和.json()
调用放入一个函数中,然后一次(立即)调用该函数,并在需要时在.catch
内再次调用它:
const getData = () => fetch("https://randomuser.me/api")
.then(result => result.json())
getData()
.then(console.log)
.catch((error) => {
console.log(error);
return getData();
});
.catch((error2) => {
// Could not get response after 2 attempts
console.log(error2);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。