Async Functions Turn Throws Into Rejections
async functions always return promises: a throw before any await becomes a rejected promise, while plain functions raise synchronous errors.
Code
// async 函数永远返回 promise:同步 throw 也会变成 rejection
async function boom() {
throw new Error('sync-looking throw');
}
boom().catch((err) => console.log('caught:', err.message));
// throw 发生在任何 await 之前也一样:调用方拿到的仍是 rejected promise
async function earlyExit(flag) {
if (!flag) throw new Error('missing flag');
return 'ready';
}
earlyExit(false).catch((err) => console.log('early:', err.message));
earlyExit(true).then((v) => console.log('ok:', v));
// 非 async 普通函数的 throw 是同步异常,必须 try/catch 接住
function plain() {
throw new Error('sync throw');
}
try {
plain();
} catch (err) {
console.log('plain needs try:', err.message);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
plain needs try: sync throw
caught: sync-looking throw
early: missing flag
ok: readyHow it works
Everything that executes sits inside the functions boom, earlyExit and plain.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The code refuses to proceed on bad state and throws Error at its guard.
Points of care
- The guard
!flagcuts the flow short right there using an earlythrowwhen its condition holds.
Using it
The main signature reads async function boom()
The demo output is labeled (caught:, early:, ok:), so the printed output reads as a trace of the operations performed.
Key statements
if (!flag) throw new Error('missing flag');
throw new Error('sync-looking throw');
throw new Error('sync throw');
Interactive Tools for This Topic
FAQ
- How does the snippet fail?
- `Error` is raised at the guard (`!flag`), so invalid state never reaches the main logic.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `boom`, `earlyExit`, `plain` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.