javascript - Promise 错误传播

标签 javascript node.js reactjs

我有这个函数,如果失败,它会重试,如果失败 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!!

enter image description here

有人可以向我解释一下为什么会发生这种情况吗?

最佳答案

避免 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/

相关文章:

node.js - 慢 Buffer.concat

node.js - 我可以在 MongoDB 中的单个查询中更新不同的文档吗?

javascript - Babel : SyntaxError: test. jsx:意外 token (3:11)

javascript - 我如何有条件地在 React 中的某些 HTML 中间包含标签

javascript - Bootstrap 4 个嵌套选项卡 : 'show all' button to display nodes in sub-tabs

javascript - Javascript 中的对象原型(prototype)属性

javascript - 使用 Angular js 进行多重选择

javascript - 如何阻止框架破坏程序破坏 WordPress 定制器页面?

node.js - 脚本内的条件。 Jade 中

css - Safari 的不同行为和样式