如何在 async/await 语法中拒绝? [英] How to reject in async/await syntax?
问题描述
如何拒绝由 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
:
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?
推荐答案
你最好的办法是 throw
一个 Error
包装值,这会导致一个被拒绝的承诺一个 Error
包装值:
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);
}
你也可以只throw
这个值,但是没有堆栈跟踪信息:
You can also just throw
the value, but then there's no stack trace information:
} catch (error) {
throw 400;
}
或者,返回一个被拒绝的承诺,其中包含一个 Error
包装值,但这不是惯用的:
Alternately, return a rejected promise with an Error
wrapping the value, but it's not idiomatic:
} catch (error) {
return Promise.reject(new Error(400));
}
(或者只是return Promise.reject(400);
,但同样,没有上下文信息.)
(Or just return Promise.reject(400);
, but again, then there's no context information.)
在你的情况下,当你使用 TypeScript
并且 foo
的返回值是 Promise
,你会使用这个:
In your case, as you're using TypeScript
and foo
's return value is Promise<A>
, you'd use this:
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.
如果你抛出一个 Error
,那么对于任何使用 await
语法消耗你的 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屋!