gpt4 book ai didi

reactjs - 无法修复未处理的拒绝错误-

转载 作者:行者123 更新时间:2023-12-03 08:43:10 24 4
gpt4 key购买 nike

我已尽力找出错误。我正在使用catch处理错误。
有人可以指出我做错了什么吗?

const get = (query: Query) => {
return new Promise((onSuccess, onFailure) => {
console.log(query.url())
fetch(query.url(), {
method: 'GET',
headers: new Headers(),
mode: 'no-cors'
})
.then(response => {
if (!response.ok) { throw Error(response.statusText) }
onSuccess(response.json())
}, error => onFailure({error})
).catch(e => onFailure(e))
})
}

unhandled rejection erro

最佳答案

首先,您应该在Promise中返回获取请求。

另外,也许我错了,但是这种错误处理非常需要:

   }, error => onFailure({error})

您已经:
).catch(e => onFailure(e))

我认为您可以像这样测试它:
const get = (query: Query) => {
return new Promise((resolve, reject) => {
//Is query.url() a request ? it can be the one which failed also.
return fetch(query.url(), {
method: 'GET',
headers: new Headers(),
mode: 'no-cors'
})
.then(response => {
if (!response.ok) {
throw Error(response.statusText)
}
return resolve(response.json())
})
.catch(e => reject(e))
})
// And also if the child request failed, your parent Promise will fail so you have to catch it well
.catch(e => {console.log(e)})
}

编辑:我忘记了一些东西,如果您在子回调中使用 throw,那么每次都无法确保它正常工作,因此也许永远不会调用 .catch之后的 throw,请尝试使用 reject而不是 throw

像这样 :
const get = (query: Query) => {
return new Promise((resolve, reject) => {
//Is query.url() a request ? it can be the one which failed also.
return fetch(query.url(), {
method: 'GET',
headers: new Headers(),
mode: 'no-cors'
})
.then(response => {
if (!response.ok) {
reject(response.statusText)
}
return resolve(response.json())
})
.catch(e => reject(e)) //the catch will be triggered
})
// And also if the child request failed, your parent Promise will fail so you have to catch it well
.catch(e => {console.log(e)})
}

如有任何疑问,请不要犹豫。
希望对你有帮助^^

关于reactjs - 无法修复未处理的拒绝错误-,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59876631/

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