gpt4 book ai didi

javascript - promise 拒绝不触发

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

我对 js 中的 Promises 比较陌生,无法理解为什么当服务器响应 401 unauthorized 时以下代码块不运行我的 catch 函数。

loginUser(email, password).then((token) => {
console.log("in then")
//ipcRenderer.send('login-success', token)
}).catch(err => {
console.log("in catch") //not running
})

登录用户函数:

function loginUser(email, password) {
let body = { email: email, password: password }

return fetch('http://localhost:3000/api/v1/sessions', {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' }
}).then(response => {
return response.json().then(json => {
console.log(response.ok) // false
return response.ok ? json : Promise.reject(json)
}).catch(err => {
console.error(err)
})
})
}

如有任何帮助,我们将不胜感激。干杯

最佳答案

来自 fetch GitHub:

https://github.com/github/fetch/issues/201

Fetch API fails only if it can't make a request. And if it can, fetch will be executed successfully even if it has a bad status.

所以听起来你的 .then( 分支将处理 401,你需要在这里处理它。

.catch( 只会在无法发出请求时执行。

关于javascript - promise 拒绝不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45270418/

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