我有这个函数,如果失败,它会重试,如果失败 x 次,它最终应该拒绝 Promise。我的实现如下:
examplefunction(retries = -1) {
return new Promise(async (resolve, reject) => {
try {
const url = `example.org`;
const json = await this._sendRequest(url);
resolve(json);
} catch (e) {
if( retries > 0 ) {
return this.examplefunction(retries - 1);
}
else {
reject("Unable to communicate with Server. Please try again later!");
}
}
});
}
该函数的调用方式如下:
backend.examplefunction(3).then(
(json) => {
console.log(json);
},
(reason) => {
console.log.(reason);
}
)
这段代码是在 React 上下文中执行的,因此它也是通过 babel transpilitaion 运行的。
我的问题是,当它在 x 次重试后最终拒绝时,会导致未捕获的 promise 错误:
Uncaught (in promise) Unable to communicate with Server. Please try again later!!
有人可以向我解释一下为什么会发生这种情况吗?
最佳答案
避免 Promise
constructor antipattern ,并且永远不要向它传递异步函数
!你应该写
async function example(retries = -1) { /*
^^^^^ */
try {
const url = `example.org`;
const json = await this._sendRequest(url);
return json;
// ^^^^^^
} catch (e) {
if (retries > 0) {
return this.examplefunction(retries - 1);
// ^^^^^^ this works as expected now
} else {
throw new Error("Unable to communicate with Server. Please try again later!");
// ^^^^^
}
}
}
在重试情况下,您从未解决
promise ,并且当递归调用最终失败时,该 promise 将被完全忽略。
关于javascript - Promise 错误传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50295615/