首页 文章

Node.JS - 无法使用try / catch块获取异步抛出

提问于
浏览
0

当我在节点中创建异步函数并使用 await 时,我正在执行等待promise解析(可能是解决或拒绝),我所做的是在try / catch块中放入 await promise并抛出承诺拒绝时的错误 . 问题是,当我在try / catch块中调用此异步函数以捕获错误时,我得到一个 UnhandledPromiseRejectionWarning . 但是使用 await 的结果是不是't waiting for the promise to resolve and return it'?看起来我的异步函数正在返回一个promise .

示例 - 代码 UnhandledPromiseRejectionWarning

let test = async () => {
let promise = new Promise((resolve, reject) => {
    if(true)
        reject("reject!");
    else resolve("resolve!");
    });
try{
    let result = await promise;
} catch(error){
    console.log("promise error =", error);
    throw error;
    }
}
let main = () =>{
    try{
        test();
    }catch(error){
        console.log("error in main() =", error);
    }
}
console.log("Starting test");
main();

2 回答

  • 0

    Main必须是异步函数才能捕获异步错误

    // wont work
    let main = () =>{
        try{
            test();
        }catch(error){
            console.log("error in main() =", error);
        }
    }
    
    // will work
    let main = async () =>{
        try{
            test();
        }catch(error){
            console.log("error in main() =", error);
        }
    }
    
  • 2

    异步函数总是返回promises . 事实上,他们总是返回本地承诺(即使你返回蓝鸟或常数) . async / await的重点是减少 .then 回调地狱的版本 . 您的程序仍然必须在main函数中至少有一个 .catch 来处理任何到达顶部的错误 .

    顺序异步调用非常好,例如;

    async function a() { /* do some network call, return a promise */ }
    
    async function b(aResult) { /* do some network call, return a promise */ }
    
    async function c() {
       const firstRes = (await (a() /* promise */) /* not promise */);
       const secondRes = await b(firstRes/* still not a promise*/);
    }
    

    如果不在函数内部,你就不能 await . 通常这意味着你的 main 函数,或者 init 或者你称之为的任何函数都不是异步的 . 这意味着它无法调用 await 并且必须使用 .catch 来处理任何错误,否则它们将是未处理的拒绝 . 在节点版本的某个时刻,这些将开始取出您的节点进程 .

    async 视为返回原生承诺 - 无论如何 - 和 await 展开承诺"synchronously" .

    • 注意异步函数返回本机承诺,它们不会同步解析或拒绝:
    Promise.resolve(2).then(r => console.log(r)); console.log(3); // 3 printed before 2
    Promise.reject(new Error('2)).catch(e => console.log(e.message)); console.log(3); // 3 before 2
    
    • 异步函数将同步错误作为被拒绝的承诺返回 .
    async function a() { throw new Error('test error'); }
    
    // the following are true if a is defined this way too
    async function a() { return Promise.reject(new Error('test error')); }
    
    /* won't work */ try { a() } catch(e) { /* will not run */ }
    
    /* will work */ try { await a() } catch (e) { /* will run */ }
    
    /* will work */ a().catch(e => /* will run */)
    

相关问题