javascript - 在 Try 中调用的 promise 未处理的 promise 拒绝

标签 javascript node.js promise

我有一个名为 findProperty 的 promise 函数,在这种情况下它会像这样拒绝:

reject('ERR: Unknown propertyID or inactive property in call of newBooking');

这是我调用 findProperty 的处理程序:

async function main() {
    var res = "";
    try { 

        findProperty();
        res = await findUser(userEmail);
        res = await findUser(agentEmail);
        res = await getUsers();

    }
    catch(err) {
        console.error(err);
        console.log(" newBooking: " + err);
        callback( { error:true, err } );
    }
}
main();

这会导致以下错误:

(node:10276) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ERR: Unknown propertyID or inactive property in call of newBooking
(node:10276) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

我不明白,我得到了我的 catch(err) 难道这还不够吗?

刚刚试了一下,效果很好:

   resolve('ERR: Unknown propertyID or inactive property in call of newBooking');

但这给出了错误:

  reject('ERR: Unknown propertyID or inactive property in call of newBooking');

最佳答案

如果 findProperty 返回一个 promise,您需要 await 它以便在异步函数的上下文中触发失败;否则排斥就会消失在外太空。

无需等待即可“触发并忘记”,但使用 try/catch 捕获失败:

findProperty().catch(e => { throw e; });

关于javascript - 在 Try 中调用的 promise 未处理的 promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44603444/

相关文章:

javascript - 嵌套异步 jquery promise

javascript - 打开新窗口,然后滚动到元素

javascript - 如何使div位置固定而不 float

javascript - 将 * 作为命令行参数传递给 Node 会产生文件和文件夹列表

Javascript:速率限制,但超过限制后继续执行

javascript - Nightmare Promises with for..loop api calls, waterfall & anti-pattern (Bluebird.js)

javascript - 有没有一种方法可以结合 Bluebird 的 `then` 和 `catch` 功能?

javascript - 内联 Javascript 未执行

javascript - 需要稍后在 Node 上执行的模块

javascript - npm:如何使用正确的依赖项创建调试和生产版本?