Javascript 承诺误差传播
我有一个函数,如果失败,它将重试,如果失败x次,它将最终拒绝承诺。我已实施了以下措施:Javascript 承诺误差传播,javascript,node.js,reactjs,Javascript,Node.js,Reactjs,我有一个函数,如果失败,它将重试,如果失败x次,它将最终拒绝承诺。我已实施了以下措施: examplefunction(retries = -1) { return new Promise(async (resolve, reject) => { try { const url = `example.org`; const json = await this._sendRequest(url);
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 Transbilitaion运行
我的问题是,当它在x次重试后最终拒绝时,会导致未捕获的承诺错误:
Uncaught (in promise) Unable to communicate with Server. Please try again later!!
有人能解释一下为什么会发生这种情况吗?避免使用异步函数,并且永远不要向它传递异步函数!你应该写
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!");
// ^^^^^
}
}
}
在重试的情况下,您从未解析过该承诺,当递归调用最终失败时,该承诺将被完全忽略。避免,并且永远不要向其传递异步函数!你应该写
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!");
// ^^^^^
}
}
}
在重试的情况下,您从未解析过该承诺,当递归调用最终失败时,该承诺被完全忽略。在引发异常之前是否记录了原因(“错误”)?是的,请参阅我添加的屏幕截图。在引发异常之前记录了原因(“错误”)?是,看到我添加的屏幕截图了吗。但是,有一件事我不太明白:当使用反模式方法并拒绝时,onRejected函数将接收一个带有错误消息的字符串,在这种方法中,它将接收一个错误对象。是的,我只是更改了它(没有注释),因为。如果你坚持的话,你当然可以抛出字符串文字。谢谢,这样就清除了它。但是,有一件事我不太明白:当使用反模式方法并拒绝时,onRejected函数将接收一个带有错误消息的字符串,在这种方法中,它将接收一个错误对象。是的,我只是更改了它(没有注释),因为。如果您坚持,当然可以抛出字符串文本。