Sub topic 18
What async Functions Return
This chapter assumes you know how to declare and call functions, how return works in ordinary functions, and the basics of Promises: .then() and what it means for a Promise to resolve or reject.
The rule: always a Promise
An async function never hands back its return value directly. It always returns a Promise. The value you give to return becomes the value that Promise resolves to.
async function getTotal() {
return 42;
}
const result = getTotal();
console.log(result instanceof Promise); // true
result.then((value) => console.log(value)); // logs 42The caller receives the Promise immediately, before the function body has necessarily finished. To get at 42, the caller uses .then() or await.
How each kind of exit maps to the Promise
| Inside the async function | The returned Promise |
|---|---|
| `return value` | Resolves to `value` |
| No `return`, or bare `return` | Resolves to `undefined` |
| `return somePromise` | Settles the same way `somePromise` does |
| `throw error` | Rejects with `error` |
The implicit undefined from earlier chapters still applies, but it comes wrapped in a Promise. Returning a Promise does not give you a Promise of a Promise. JavaScript unwraps it, so the caller sees a single level.
Errors become rejections
A throw inside an async function does not escape to the caller as a synchronous exception. It rejects the returned Promise, so a plain try/catch around the call will not catch it unless you await the call.
async function loadUser(id) {
if (!id) throw new Error("id is required");
return { id, name: "Ana" };
}
async function main() {
try {
const user = await loadUser(1);
console.log(user.name); // "Ana"
await loadUser(); // rejects
} catch (err) {
console.log(err.message); // "id is required"
}
}
main();The common mistake: forgetting await
Callers often forget that they hold a Promise and not the value. The code runs without errors and quietly produces nonsense.
async function getPrice() {
return 100;
}
async function checkout() {
const wrong = getPrice(); // a Promise, not 100
console.log(wrong * 0.9); // NaN
const right = await getPrice(); // 100
console.log(right * 0.9); // 90
}
checkout();Exercise
What does this code log, and in what order? async function f() { console.log("A"); return "B"; } f().then(console.log); console.log("C");
Show answer
It logs "A", then "C", then "B". The body runs synchronously until it returns, so "A" prints first. The returned Promise is already resolved, but .then callbacks always run asynchronously, so "C" prints before "B".
Exercise
An async function save() has no return statement. What is the type of save(), and what does await save() evaluate to?
Show answer
save() returns a Promise. await save() evaluates to undefined, because a function with no return resolves its Promise to undefined.