【问题标题】:Unhandled promise rejection from promise called within Try在 Try 中调用的 Promise 中未处理的 Promise 拒绝
【发布时间】:2017-11-20 01:39:32
【问题描述】:

我有一个名为 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');

【问题讨论】:

    标签: javascript node.js promise


    【解决方案1】:

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

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

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

    【讨论】:

    • 所以你不能在不想等待回复的地方使用普通的承诺?我以为你可以混搭。
    • 实际上你是对的@torazaburo - 一旦我输入res = await findProperty(); 就可以了。那么,我的问题是,我如何全力以赴并忘记承诺?我有很多不想等待结果的地方。
    • @torbenrudgaard 是的。但是你需要提供一个像 findProperty().catch(console.log.bind(console)); 这样的捕获。或者干脆不拒绝他们
    • @Jonasw ahhhh... okieee.. 我想我明白了。所以我给他们一个单独的捕获,这样我就可以在控制台或其他任何东西上打印。不知道你能做到这一点,谢谢。 console.log.bind 是什么?以前从未见过绑定?
    • @torbenrudgaard 传递 console.log 只是传递 log ,如果你这样做它会说 error, log isnt part of a console instance ,就是这样为什么需要将控制台绑定到它。或者你这样做: .catch(e=>console.log(e));没有通过引用所以没有问题...
    猜你喜欢
    • 2019-04-15
    • 2019-02-28
    • 2018-03-19
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    相关资源
    最近更新 更多