JavaScriptFundamental (ES6), part 2
Why async functions never throw synchronously in JavaScript
40 An async function never throws synchronously
fairWrite an async function that throws on a bad argument and call it inside a plain try/catch without awaiting. Show that nothing is caught, that a promise came back instead, and that the body still ran synchronously up to the throw. Then restore a synchronous throw with a plain wrapper.
Stuck? Three hints, smallest first
- 1. An
asyncfunction converts every completion — value or throw — into a settled promise. - 2. The body does run immediately, up to the first
await. Only the resumption is deferred. - 3. To fail fast on bad arguments, validate in a normal function that then calls the async one.
const order = [];
async function chargeTill(amount) {
order.push('body starts, synchronously');
if (amount <= 0) throw new RangeError('amount must be positive');
await Promise.resolve();
order.push('body resumes, a tick later');
return `charged ₦${amount}`;
}
let syncCatch = 'nothing was thrown at the call site';
let returned;
try {
returned = chargeTill(-1);
} catch {
syncCatch = 'caught synchronously';
}
order.push('caller carries on');
const promiseShape = [typeof returned.then, returned instanceof Promise, returned.constructor.name];
const asRejection = await returned.then(() => 'resolved', (err) => err.name);
const orderAtThatPoint = order.slice();
const plainNumber = async () => 42;
const beforeAwait = plainNumber();
const wrapped = [typeof beforeAwait.then, await beforeAwait];
const receipt = await chargeTill(2500);
// Validate in a synchronous wrapper, and a bad call fails at the call site again.
const chargeGuarded = (amount) => {
if (amount <= 0) throw new RangeError('amount must be positive');
return chargeTill(amount);
};
let guarded = 'still nothing';
try { chargeGuarded(-1); } catch (err) { guarded = err.name; }
console.log('sync try/catch :', syncCatch);
console.log('what came back :', promiseShape, '-> rejects with', asRejection);
console.log('order :', orderAtThatPoint);
console.log('guarded call :', guarded);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an async function that throws does not throw at the call site', syncCatch, 'nothing was thrown at the call site');
test('it hands back a promise instead', promiseShape, ['function', true, 'Promise']);
test('and the throw arrives later, as a rejection', asRejection, 'RangeError');
test('yet the body really did run up to the throw before the caller moved on', orderAtThatPoint, ['body starts, synchronously', 'caller carries on']);
test('returning a plain number still gives you a promise', wrapped, ['function', 42]);
test('which awaits to the value like anything else', receipt, 'charged ₦2500');
test('the resumed half of a body runs after the caller has carried on', order.at(-1), 'body resumes, a tick later');
test('validating in a plain wrapper is what restores a synchronous throw', guarded, 'RangeError');
async is a promise around a function body, and that includes its failures. Every way the body can end — a value, a throw, a rejected await — comes out as a settled promise, so a try/catch that does not await is watching the wrong thing entirely. It sees the function return successfully, because returning a rejected promise is returning successfully.
The fourth assertion is the half people get wrong in the other direction. Calling an async function is not lazy: the body runs immediately and synchronously up to the first await. So argument validation at the top does execute at once — it simply cannot throw at once, because the throw is captured and converted. Deferred delivery, not deferred execution.
Why the guarded version is worth the extra function: a bad argument is a programming error, and you want it at the call site, in the caller's stack, with no promise involved. Everything else — network, disk, the card network — is a runtime failure and belongs in the rejection. Splitting the two is also what makes a mistyped call fail in a unit test rather than in a log file.
One consequence worth remembering: fetch is not async-shaped in this respect. Some platform functions do throw synchronously on a malformed argument. Wrapping a call in try/catch and attaching a catch to the promise is not paranoia if you do not control the callee.