简体   繁体   English

从匿名函数内部的函数返回

[英]Return from function from inside anonymous function

I have the following function. 我有以下功能。

function foo() {
  return new Promise(async (resolve, reject) => {
     await someFunctionThatWillAlwaysBeRejected().catch(err => {
       return reject(err);
     })
     console.log("Some output that should never be shown");
     resolve();
   })
  }

The function rejects as expected but after it continues to run until the end. 该函数将按预期方式拒绝,但此后它将继续运行直到结束。 I guess it's because the return inside the catch only returns from the anonymous function and not from the entire Promise . 我想这是因为return渔获内只能从匿名函数返回,而不是从整个Promise The question is if there is any way of returning from inside the catch so the code won't continue to execute after that? 问题是,是否有任何从catch内返回的方法,这样代码在那之后将不会继续执行? I know I can wrap everything in try catch instead of using .catch but I'm trying to avoid that. 我知道我可以将所有内容包装在try catch而不是使用.catch但是我正试图避免这种情况。

The question is if there is any way of returning from inside the catch 问题是,是否有任何方法可以从渔获物内部返回

No. 没有。

I know I can wrap everything in try catch instead of using .catch but I'm trying to avoid that. 我知道我可以将所有内容包装在try catch中,而不是使用.catch,但是我正试图避免这种情况。

async / await allows you to do that precisely so you can solve the problem you have. async / await允许您精确地执行此操作,从而可以解决您遇到的问题。 Stop avoiding it. 停止避免它。

Try this : 尝试这个 :

return new Promise(async (resolve, reject) => {
 someFunctionThatWillAlwaysBeRejected().then(result => {
   console.log("Some output that should never be shown");
   resolve();
 })
 .catch(err => {
   return reject(err);
 })

})

You don't need those promise wrapper, because async function is always return Promise. 您不需要那些promise包装器,因为异步函数总是返回Promise。 Therefore, your code could be simplified: 因此,您的代码可以简化:

async function foo() {
     await someFunctionThatWillAlwaysBeRejected();
     console.log("Some output that should never be shown");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM