Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

javascript - 如何在async / await语法中拒绝?(How to reject in async/await syntax?)

How can I reject a promise that returned by an async/await function?(如何拒绝async / await函数返回的promise?)

eg Originally(例如,最初) foo(id: string): Promise<A> { return new Promise((resolve, reject) => { someAsyncPromise().then((value)=>resolve(200)).catch((err)=>reject(400)) }); } Translate into async/await(转换为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?(那么,在这种情况下,我怎么能正确地拒绝这个承诺呢?)   ask by Phoenix translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your best bet is to throw an Error wrapping the value, which results in a rejected promise with an Error wrapping the value:(你最好的办法是throw一个Error包装值,这会导致一个被拒绝的承诺,并包含一个Error值:)

} catch (error) { throw new Error(400); } You can also just throw the value, but then there's no stack trace information:(您也可以throw值,但是没有堆栈跟踪信息:) } catch (error) { throw 400; } Alternately, return a rejected promise with an Error wrapping the value:(或者,返回一个被拒绝的promise,其中包含一个Error :) } catch (error) { return Promise.reject(new Error(400)); } (Or just return Promise.reject(400); , but again, then there's no context information.)((或者只return Promise.reject(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*/); )((在你的情况下,当你使用TypeScriptfoo的retrn值是Promise<A> ,你会使用return Promise.reject<A>(400 /*or error*/); )) In an async / await situation, that last is probably a bit of a semantic mis-match, but it does work.(在async / await情况下,最后一个可能是语义不匹配,但确实有效。) If you throw an Error , that plays well with anything consuming your foo 's result with await syntax:(如果你抛出一个Error ,那么使用await语法消耗foo结果的任何东西都能很好地运行:) 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`. }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...