JavaScriptFundamental (ES6), part 1
What async functions return in JavaScript
87 What await accepts, and what async hands back
fairShow that an async function returns a promise no matter what its body returns, that await is happy with a plain value or with any object that has a then method, and that a throw inside becomes a rejection. Then find where the body of an async function actually stops running.
Stuck? Three hints, smallest first
- 1. Call an async function without awaiting it and look at what you are holding: check
typeof it.then. - 2. An object with a
then(resolve, reject)method is a thenable, andawaittreats it like a promise.Promise.resolvewraps it; a native promise it hands straight back. - 3. Put a
pushbefore the firstawaitand one after it, then read the array before awaiting the call.
const fareAsync = async (km) => km * 1500;
const pending = fareAsync(10);
const kind = [typeof pending.then, pending instanceof Promise];
const fare = await pending;
const trace = [];
const dispatch = async () => {
trace.push('body');
await null; // the first suspension, however trivial
trace.push('after');
};
const running = dispatch();
const atOnce = [...trace];
await running;
const atEnd = [...trace];
let thenCalls = 0;
const thenable = {
then(resolve) {
thenCalls++;
resolve('paid by thenable');
},
};
const fromThenable = await thenable;
const dry = async () => {
throw new Error('no fuel');
};
let caught;
try {
await dry();
} catch (error) {
caught = error.message;
}
const viaCatch = await dry().catch((error) => `handled: ${error.message}`);
const inner = Promise.resolve('adopted');
const outer = async () => inner; // returning a promise, not a value
const once = await outer();
const twice = await await Promise.resolve('one level only');
const native = Promise.resolve(1);
const identity = [Promise.resolve(native) === native, Promise.resolve(thenable) === thenable];
const parse = (src) => {
try { new Function(src); return 'compiled'; } catch (error) { return error.constructor.name; }
};
const outsideAsync = parse('return await Promise.resolve(1);');
console.log('returned :', kind, '| value:', fare);
console.log('trace :', atOnce, '->', atEnd);
console.log('thenable :', fromThenable, '| then called', thenCalls, 'time(s)');
console.log('rejection :', caught, '|', viaCatch);
console.log('adoption :', once, twice, '| identity:', identity, '| outside async:', outsideAsync);
Output
9 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 9 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 returns a promise, whatever its body returns', kind, ['function', true]);
test('and the returned value comes out of the await', fare, 15000);
test('the body runs synchronously up to the first await, then stops', [atOnce, atEnd], [['body'], ['body', 'after']]);
test('await accepts any object with a then method, and calls it once', [fromThenable, thenCalls], ['paid by thenable', 1]);
test('a throw inside an async function is a rejection, catchable with try', caught, 'no fuel');
test('and the same rejection is reachable through .catch on the promise', viaCatch, 'handled: no fuel');
test('a returned promise is adopted, so one await is enough and two change nothing', [once, twice], ['adopted', 'one level only']);
test('Promise.resolve returns a native promise unchanged, but wraps a thenable', identity, [true, false]);
test('await outside an async function does not compile at all', outsideAsync, 'SyntaxError');
async is a wrapper on the return value and await is a wrapper on the argument, and both are more forgiving than they look. Whatever the body returns comes back as a promise, so typeof x.then === 'function' is the only thing a caller can rely on. Whatever you await is put through Promise.resolve first, so awaiting 41, a thenable from some library, or a real promise all work — which is what makes await safe to write in front of a value that might or might not be asynchronous.
The trace is the part people get wrong. Calling an async function does not schedule it for later; the body runs immediately, on the spot, until it reaches the first await. Everything after that await is a continuation queued as a microtask. So a synchronous side effect at the top of an async function has already happened by the time the call returns, while the same line moved one place down has not.
Two things follow. A throw anywhere in the body becomes a rejection of the returned promise rather than an exception at the call site, so it is invisible unless someone awaits or catches it — an async function whose result is dropped swallows its own errors. And returning a promise from an async function adopts it rather than nesting it: there is no Promise<Promise<T>> to unwrap, which is why await await p is the same as await p.