如何在async / await语法中拒绝? [英] How to reject in async/await syntax?

查看:505
本文介绍了如何在async / await语法中拒绝?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何拒绝async / await函数返回的承诺?

How can I reject a promise that returned by an async/await function?

例如。最初

foo(id: string): Promise<A> {
  return new Promise((resolve, reject) => {
    someAsyncPromise().then((value)=>resolve(200)).catch((err)=>reject(400))
  });
}

转换为async / await

Translate into async/await

async foo(id: string): Promise<A> {
  try{
    await someAsyncPromise();
    return 200;
  } catch(error) {//here goes if someAsyncPromise() rejected}
    return 400; //this will result in a resolved promise.
  });
}

那么,在这种情况下我怎么能正确拒绝这个承诺?

So, how could I properly reject this promise in this case?

推荐答案

你最好的选择是抛出一个错误包装该值,导致被拒绝的承诺,错误包装值:

Your best bet is to throw an Error wrapping the value, which results in a rejected promise with an Error wrapping the value:

} catch (error) {
    throw new Error(400);
}

你也可以抛出值,但是没有堆栈跟踪信息:

You can also just throw the value, but then there's no stack trace information:

} catch (error) {
    throw 400;
}

或者,返回一个被拒绝的承诺,其中包含错误包装值:

Alternately, return a rejected promise with an Error wrapping the value:

} catch (error) {
    return Promise.reject(new Error(400));
}

(或者只是返回Promise.reject(400) ; ,但是再次没有上下文信息。)

(Or just return Promise.reject(400);, but again, then there's no context information.)

(在您的情况下,因为您正在使用 TypeScript foo 的后续值是 Promise< A> ,你会用返回Promise.reject< A>(400 / *或错误* /);

(In your case, as you're using TypeScript and foo's retrn value is Promise<A>, you'd use return Promise.reject<A>(400 /*or error*/);)

async / await 情况,最后一点可能是语义不匹配,但确实有效。

In an async/await situation, that last is probably a bit of a semantic mis-match, but it does work.

如果你抛出一个错误,这对消费你的 foo 的结果等待语法:

If you throw an Error, that plays well with anything consuming your foo's result with await syntax:

try {
    await foo();
} catch (error) {
    // Here, `error` would be an `Error` (with stack trace, etc.).
    // Whereas if you used `throw 400`, it would just be `400`.
}

这篇关于如何在async / await语法中拒绝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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