【问题标题】:Promise error propagation承诺错误传播
【发布时间】:2018-10-22 01:34:04
【问题描述】:

我有这个函数,如果它失败重试,如果失败 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 重试后最终拒绝时,这会导致 Uncaught Promise 错误:

Uncaught (in promise) Unable to communicate with Server. Please try again later!!

谁能向我解释为什么会这样?

【问题讨论】:

  • 在抛出异常之前是否记录原因(“错误”)?
  • 是的,看我添加的截图

标签: javascript node.js reactjs


【解决方案1】:

避免使用Promise constructor antipattern,并且永远不要将async function 传递给它!你应该写

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!");
//          ^^^^^
        }
    }
}

在重试的情况下,你从来没有 resolveing 承诺,当递归调用最终失败时,承诺被完全忽略。

【讨论】:

  • 谢谢这清除它。然而,我不太明白的一件事是:当使用反模式方法并拒绝时,onRejected 函数将收到一个带有错误消息的字符串,但在这种方法中它会收到一个错误对象。
  • 是的,我只是更改了它(没有评论)因为you should always reject with errors, not strings。如果您坚持,您当然可以throw 字符串文字。
猜你喜欢
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-11
  • 1970-01-01
  • 1970-01-01
  • 2015-10-31
  • 1970-01-01
相关资源
最近更新 更多