Sub topic 20
What async Functions Return
This chapter assumes you know how to create and consume a Promise with .then() and .catch(), and that you have seen await used inside an async function. It builds on the earlier chapters about return, implicit undefined, arrow functions, and the required-parameter pattern.
The rule is short. An async function always returns a Promise. Whatever you write after return becomes the value that Promise settles with, and the caller never receives that value directly.
The Promise Wrapper
Here is the smallest example:
async function getTotal() {
return 42;
}
const result = getTotal();
console.log(result instanceof Promise); // true
result.then((value) => console.log(value)); // logs 42Calling getTotal() does not give you 42. It gives you a Promise that is already resolved, or about to be, with 42. To get the number, the caller uses .then() or await.
This applies to every async function, whatever its body contains:
async function nothing() {}
async function fail() {
throw new Error("boom");
}
nothing().then((value) => console.log(value)); // logs undefined
fail().catch((err) => console.log(err.message)); // logs "boom"The implicit undefined from earlier chapters still applies. It just arrives inside a Promise. A thrown error does not escape the call either. The async function catches it and turns it into a rejected Promise.
How the Returned Promise Settles
The table below shows what the caller sees for each kind of exit from an async function.
| Inside the async function | Returned Promise |
|---|---|
| `return 42;` | Fulfilled with `42` |
| No `return`, or bare `return;` | Fulfilled with `undefined` |
| `return somePromise;` | Follows `somePromise`: fulfilled or rejected with its result |
| `throw new Error("x");` | Rejected with that error |
| An awaited Promise rejects and is not caught | Rejected with that reason |
| A default parameter expression throws | Rejected with that error |
Returned Promises are not nested
When you return a Promise from an async function, you do not get a Promise of a Promise. The outer Promise adopts the inner one's result:
async function delayed() {
return new Promise((resolve) => {
setTimeout(() => resolve("done"), 100);
});
}
delayed().then((value) => console.log(value)); // logs "done", not a PromiseAny thenable gets the same treatment. A thenable is an object with a then method. Because of this flattening, await always hands you a plain value, however many layers of Promise were involved.
Errors in parameters reject too
The required-parameter pattern from an earlier chapter behaves differently inside an async function. When a default expression throws, the error becomes a rejection, just like an error thrown in the body:
function required(name) {
throw new Error(`Missing parameter: ${name}`);
}
async function connect(url = required("url")) {
return `Connecting to ${url}`;
}
connect().catch((err) => console.log(err.message)); // logs "Missing parameter: url"If the caller does not handle that rejection, the missing argument shows up only as an unhandled-rejection warning. Nothing is thrown at the call site.
`return` Versus `return await`
Outside a try block, return promise and return await promise give the caller the same result. Inside a try block they behave differently:
async function load() {
throw new Error("network");
}
async function withoutAwait() {
try {
return load(); // the Promise leaves the try block before it rejects
} catch {
return "fallback";
}
}
async function withAwait() {
try {
return await load(); // the rejection is thrown here, inside try
} catch {
return "fallback";
}
}
withoutAwait().catch((err) => console.log("rejected:", err.message)); // rejected: network
withAwait().then((value) => console.log("resolved:", value)); // resolved: fallbackIn withoutAwait, the return hands the pending Promise outward right away, and the function exits the try block. The later rejection skips the catch. In withAwait, await pauses inside the try block, so the rejection is thrown there and caught. A finally block follows the same rule: with return await, the finally runs after the awaited work finishes.
Common Errors
Treating the Promise as the value
A Promise object is always truthy, so a missing await in a condition fails silently:
async function isAdmin(user) {
return user.role === "admin";
}
async function main() {
const user = { role: "viewer" };
if (isAdmin(user)) {
console.log("Bug: this always runs, because a Promise is truthy");
}
if (await isAdmin(user)) {
console.log("This never runs for a viewer");
}
}
main();The same bug produces "[object Promise]" inside template literals and NaN in arithmetic. If a value looks wrong, check whether you forgot await.
Expecting `await` at the top level of a script
await works only inside async functions and at the top level of ES modules. In a CommonJS file or a classic script, wrap the code in an async function, or use .then().
Changing a sync function to async
Adding async to an existing function changes its return type for every caller. Code that did const total = getTotal(); now gets a Promise. Treat this as a breaking change to the function's signature and update every call site.
Combining With Earlier Patterns
Everything you know about return values still works. You just unwrap the Promise first. An async arrow function returns its expression implicitly, and an object literal still needs parentheses:
const fetchPoint = async (x, y) => ({ x, y });
async function fetchStats(nums) {
const total = nums.reduce((a, b) => a + b, 0);
return { total, mean: total / nums.length };
}
async function main() {
const { x, y } = await fetchPoint(1, 2);
const { mean } = await fetchStats([2, 4, 6]);
console.log(x, y, mean); // 1 2 4
const [point, stats] = await Promise.all([fetchPoint(3, 4), fetchStats([1, 3])]);
console.log(point.x, stats.total); // 3 4
}
main();Promise.all runs several async calls at once and fulfills with an array of their results in order. You destructure that array as if it were a synchronous multi-value return. If any of the calls rejects, the combined Promise rejects.
Exercise
What does this code log, and in what order? async function a() { return Promise.resolve(5); } followed by const p = a(); console.log(typeof p); p.then((v) => console.log(typeof v, v));
Show answer
It logs "object" first, because p is a Promise and that line runs synchronously. Later it logs "number 5". The Promise returned from a adopts the inner Promise's value, so v is the number 5 and not a nested Promise.
Exercise
A teammate writes async function save(data) { try { return db.write(data); } catch (e) { log(e); return null; } }. When db.write rejects, nothing is logged and callers see a rejection. Why, and what is the fix?
Show answer
return db.write(data) passes the pending Promise outward and exits the try block before the Promise rejects, so the catch never runs. The fix is return await db.write(data);. That way the rejection is thrown inside the try block, the catch logs it, and the function resolves with null.
Exercise
Why does async function f(x = required("x")) {} followed by a call to f() not crash the program at the call site, and how should the caller detect the missing argument?
Show answer
In an async function, an error from a default parameter expression becomes a rejection of the returned Promise and is not thrown synchronously. The caller has to handle it with await f() inside try/catch, or with f().catch(...).