Node.JS-无法通过try/catch块获得异步抛出 [英] Node.JS - Can`t get async throws with try/catch blocks

查看:201
本文介绍了Node.JS-无法通过try/catch块获得异步抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在节点中创建一个异步函数并使用 await 时,我正在使执行等待一个Promise解决方案(可以是解决方案或拒绝方案),我要做的是在try/catch块中 await 承诺,并在承诺被拒绝的情况下引发错误.问题是,当我在try/catch块中调用此异步函数以捕获错误时,会得到 UnhandledPromiseRejectionWarning .但是,使用 await 的全部目的不是在等待承诺解决并返回结果吗?看来我的异步功能正在返回承诺.

When I create an async function in node and use await, I'm making the execution waits for a promise resolution (that can be a resolve or a rejection), what I do is put an await promise inside a try/catch block and throw an error in case of a promise rejection. The problem is, when I call this async function inside a try/catch block to catch the error in case of it, I get an UnhandledPromiseRejectionWarning. But the whole point of using await isn't waiting for the promise to resolve and return it's result? It seems like my async function is returning a 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();

推荐答案

异步函数始终返回承诺.实际上,它们总是返回本机的Promise(即使您返回了蓝鸟或常量).异步/等待的目的是减少.then回调地狱的版本.您的程序仍必须在主函数中至少具有一个.catch,以处理到达顶部的所有错误.

async functions always return promises. In fact, they always return native promises (even if you returned a bluebird or a constant). The point of async/await is to reduce the version of .then callback hell. Your program will still have to have at least one .catch in the main function to handle any errors that get to the top.

对于顺序异步调用来说真的很好,例如;

It is really nice for sequential async calls, e.g.;

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来处理任何错误,否则将被未处理的拒绝.在节点版本中的某些时候,这些将开始删除您的节点进程.

You cannot await something without being inside a function. Usually this means your main function, or init or whatever you call it, is not async. This means it cannot call await and must use .catch to handle any errors or else they will be unhandled rejections. At some point in the node versions, these will start taking out your node process.

async视为返回本机承诺-无论什么-和await视为同步"展开承诺.

Think about async as returning a native promise - no matter what - and await as unwrapping a promise "synchronously".

  • note异步函数返回本机promise,该promise不同步解析或拒绝:

  • note async functions return native promises, which do not resolve or reject 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 functions return sync errors as rejected promises.

    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 */)
    
    /* won't _always_ work */ try { return a(); } catch(e) { /* will not usually run, depends on your promise unwrapping behavior */ }
    

  • 这篇关于Node.JS-无法通过try/catch块获得异步抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆