{ const opts = { credentials: 'same-origin', }; -6ren">
gpt4 book ai didi

javascript - "Uncaught (in promise) "在 fetch 'then' 方法中调用 reject 函数时

转载 作者:数据小太阳 更新时间:2023-10-29 04:10:16 30 4
gpt4 key购买 nike

这里是有问题的代码:

new Promise((resolve, reject) => {
const opts = {
credentials: 'same-origin',
};

fetch(`/_api/myAPI`, opts)
.then((res) => {
if (!res.ok) {
reject(res);
} else {
...

如果 url 抛出异常 a 401,当执行到 reject(res); 时它抛出 Uncaught (in promise)

即使我在 .then 调用之后添加了一个 .catch,即

  fetch(`/_api/myAPI`, opts)
.then((res) => {
if (!res.ok) {
reject(res);
} else {
...
})
.catch((e) => {
console.log(e);
}

它仍然发生。

为什么 reject 会抛出这个异常,我该如何解决?我的经验仅限于 jQuery.Promise 并且我不会在失败处理程序中使用 reject 来触发此错误。

最佳答案

当您拒绝 promise 时,您会立即拒绝包装整个操作的 promise ,因此您永远不会到达那个 catch block 。

打个比方:reject 和 resolve 之于 promises 就像 return 之于函数。

我想你正在尝试做的是下面的代码。

new Promise((resolve, reject) => {
const opts = {
credentials: 'same-origin',
};
fetch(`/_api/myAPI`, opts)
.then((res) => {
if (!res.ok) {
return Promise.reject()
} else {
...
resolve(...);
})
.catch((e) => {
console.log(e);
reject();
}
}

关于javascript - "Uncaught (in promise) "在 fetch 'then' 方法中调用 reject 函数时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806239/

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