Hone

Lessons · TypeScript · async always hands back a promise

An async function always returns a promise

Marking a function async wraps its return value in a Promise. return 1 becomes a promise that resolves to 1, and a throw becomes a rejected promise.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Every fetch, every file read, every timer in modern JavaScript flows through promises. The rule that async returns a promise is why callers must await, and why forgetting to is silent.

How to think about it

Treat the result of any async call as a promise: await it inside another async function, or chain .then. If a variable holds a Promise where you expected data, an await is missing.

Worked example

async function one() { return 1; }
Returns 1, wrapped.
console.log(one() instanceof Promise);
true: an async function always returns a Promise.
one().then(v => console.log(v));
1: the value arrives through then, or await.
async function boom() { throw new Error("no"); }
A throw inside async.
boom().catch(e => console.log(e.message));
no: the throw became a rejected promise.

Your turn

Make the loader asynchronous.

 function load() { return fetch(url); }

The trap

Forgetting await: const data = load(); gives a Promise, and data.items is undefined. Nothing warns you.

Practise async always hands back a promise on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.