Sub topic 4
Async Functions Always Return a Promise
This chapter assumes you can create Promises, attach handlers with then, catch, and finally, and read a short promise chain. You should also be comfortable with arrow functions, object methods, and classes. The await operator gets its own chapter next. Here, the focus is on the outside of an async function: what a caller receives, when the function body runs, and how returned values and thrown errors turn into Promise states.
The one rule
Putting the async keyword before a function changes its contract with callers. Whatever the body does, the caller always gets a Promise back. A plain value becomes the fulfillment value. A thrown error becomes the rejection reason. If the body returns a Promise, the caller's Promise follows that Promise's outcome.
async function getNumber() {
return 42;
}
console.log(getNumber() instanceof Promise); // true
getNumber().then(value => console.log(value)); // 42getNumber looks like it returns 42, but calling it gives you a Promise that fulfills with 42. To get the number, you attach then or use await from another async function.
Every way to write an async function
You can use async with every function form except getters, setters, and constructors. The rule about the return value is the same for all of them.
async function declared() { return 'declaration'; }
const expressed = async function () { return 'expression'; };
const arrow = async () => 'arrow';
const obj = { async method() { return 'method'; } };
class Service { async load() { return 'class method'; } }
const calls = [
declared,
expressed,
arrow,
() => obj.method(),
() => new Service().load()
];
for (const call of calls) {
call().then(value => console.log(value));
}
// declaration, expression, arrow, method, class methodThe concise arrow form async () => 'arrow' works the same as the block form: its expression is the return value, and that value gets wrapped. An async function that never uses await is still valid. It is just a function that returns a Promise.
What happens to the returned Promise
The table below shows how each kind of exit from the body settles the Promise the caller holds.
| What the body does | State of the returned Promise | Value or reason |
|---|---|---|
| `return 42` | fulfilled | `42` |
| Reaches the end with no `return` | fulfilled | `undefined` |
| `return` with no value | fulfilled | `undefined` |
| `throw new Error('x')` | rejected | the `Error` object |
| `return somePromise` that fulfills | fulfilled | that Promise's value |
| `return somePromise` that rejects | rejected | that Promise's reason |
| `return thenable` (an object with a `then` method) | follows the thenable | whatever the thenable passes on |
Thrown errors become rejections, not exceptions
This difference catches many people. A regular function that throws sends the exception straight up the call stack, so a surrounding try/catch catches it. An async function that throws does not throw at the call site. The error is stored in the returned Promise.
function syncFail() {
throw new Error('sync boom');
}
async function asyncFail() {
throw new Error('async boom');
}
try {
syncFail();
} catch (err) {
console.log('caught synchronously:', err.message);
}
try {
const p = asyncFail();
console.log('no exception at call site; got a Promise:', p instanceof Promise);
p.catch(err => console.log('caught via the Promise:', err.message));
} catch (err) {
console.log('this line never runs');
}
// caught synchronously: sync boom
// no exception at call site; got a Promise: true
// caught via the Promise: async boomThis even covers errors that look synchronous, such as reading a property of undefined on the first line of the body. Callers handle every error from an async function the same way, through the Promise. That consistency is useful. It also means a surrounding try/catch without await gives you no protection.
Returning a Promise adopts it, it does not nest it
If the body returns a Promise, the caller does not receive a Promise of a Promise. The returned Promise resolves with the inner one, and resolution unwraps it. However, the caller receives a new Promise object, not the one you returned.
const inner = Promise.resolve('inner value');
async function passThrough() {
return inner;
}
const outer = passThrough();
console.log(outer === inner); // false: a new Promise
console.log(Promise.resolve(inner) === inner); // true: Promise.resolve reuses native Promises
outer.then(value => console.log(value)); // 'inner value', not a PromiseAdoption also works for thenables, which are objects with a then method. This is how async functions work with older Promise libraries.
const thenable = {
then(resolve) {
resolve('from thenable');
}
};
async function useThenable() {
return thenable;
}
useThenable().then(value => console.log(value)); // 'from thenable'Adopting a Promise costs a few extra microtask turns compared with returning a plain value. In normal code this does not matter. It can change the exact order of logs in tricky output-ordering puzzles, which the microtasks chapter covers.
The body starts running immediately
Calling an async function does not schedule the body for later. The body runs synchronously, right away, on the current call stack, until it hits its first await or finishes. Only the settlement of the Promise is delivered asynchronously, because then callbacks always run as microtasks.
async function work() {
console.log('2: inside the body');
return 'result';
}
console.log('1: before the call');
const p = work();
console.log('3: after the call');
p.then(value => console.log('4:', value));
// 1: before the call
// 2: inside the body
// 3: after the call
// 4: resultThe Promise p is already fulfilled when line 3 runs. Its handler still waits until the current synchronous code is done. That is why 4 prints last. This rule also means that marking a function async does not move heavy computation off the main thread. A CPU-bound loop inside an async function blocks the page or the server just as much as it would in a regular function.
A rough desugaring
For an async function without await, you can model the behavior with the Promise constructor:
// async function getNumber() { return 42; }
// behaves roughly like:
function getNumberManual() {
return new Promise((resolve, reject) => {
try {
const result = 42; // the original body runs here, synchronously
resolve(result); // resolve adopts Promises and thenables
} catch (err) {
reject(err);
}
});
}
getNumberManual().then(value => console.log(value)); // 42This model accounts for all three behaviors from this chapter: the body runs synchronously inside the executor, thrown errors become rejections, and resolve unwraps returned Promises. Once you add await, the engine also has to suspend and resume the body, which this simple model cannot show. That is the subject of the next chapter.
Common errors that come from forgetting the rule
Treating the Promise as the value
A Promise is an object, and every object is truthy. A condition that tests an async function's result directly always passes.
async function isAdmin(user) {
return user.role === 'admin';
}
const guest = { role: 'guest' };
if (isAdmin(guest)) {
console.log('Bug: this always runs, because a Promise is truthy');
}
isAdmin(guest).then(ok => console.log('actual result:', ok)); // falseThe same mistake shows up in other ways. JSON.stringify(promise) produces "{}". Adding a Promise to a number gives a string such as "[object Promise]1". A template literal prints [object Promise]. When you see one of these, check whether a call to an async function is missing an await or a then.
Mapping with an async callback
map collects whatever the callback returns. With an async callback, that is a Promise for every element.
const doubled = [1, 2, 3].map(async n => n * 2);
console.log(doubled.every(item => item instanceof Promise)); // true
Promise.all(doubled).then(values => console.log(values)); // [ 2, 4, 6 ]Promise.all turns the array of Promises into one Promise for the array of values. The later chapters on combinators and pitfalls cover this pattern, along with the related forEach problem, in more detail.
Changing a function to async breaks its callers
Adding async to an existing function changes its return type. Every caller that used the return value directly now receives a Promise, and every caller that wrapped the call in try/catch no longer catches its errors. Treat this as a breaking API change. Search for all call sites and update them. In TypeScript, the compiler helps here: an async function's declared return type must be Promise<T>, so mismatched callers produce type errors.
Returning a value from a callback API inside an async function
Returning a value from inside a callback, for example inside a setTimeout callback, does not fulfill the outer async function's Promise. The outer body has already finished and fulfilled with undefined. To connect callback-based APIs to async code, wrap them in new Promise and return that Promise, as the delay helper in later chapters does.
Summary of the contract
- Calling an async function always returns a new native Promise.
- The body runs synchronously until its first
awaitor until it finishes. return valuefulfills the Promise. Falling off the end fulfills it withundefined.throwrejects the Promise. Nothing is thrown at the call site.- Returning a Promise or thenable makes the outer Promise adopt its outcome, without nesting.
Exercise
Predict the full console output, in order, and explain each line. async function f() { console.log('f start'); throw new Error('nope'); } console.log('before'); const p = f(); console.log('after', typeof p); p.then(() => console.log('fulfilled')) .catch(err => console.log('rejected:', err.message));
Show answer
The output is "before", "f start", "after object", "rejected: nope". The body of f runs synchronously during the call, so "f start" prints before the call returns. The throw does not escape to the caller. It rejects p, so "after object" prints next (typeof a Promise is "object"). The then handler is skipped because p is rejected, and the catch handler runs as a microtask after the synchronous code finishes.
Exercise
A teammate writes async function getConfig() { return loadConfigPromise; }, where loadConfigPromise is an existing Promise that fulfills with an object. They expect getConfig() === loadConfigPromise to be true and getConfig().then(c => typeof c) to produce "object". Which expectation is correct, and why?
Show answer
Only the second one is correct. An async function always returns a new Promise, so the identity check is false (unlike Promise.resolve, which returns a native Promise unchanged). The new Promise adopts the inner Promise's state instead of wrapping it, so the then handler receives the config object itself, and typeof gives "object".
Exercise
This check never blocks banned users: if (!isBanned(user)) allowLogin(user);, where isBanned is an async function. Explain the bug and rewrite the check using then.
Show answer
isBanned returns a Promise, which is always truthy, so !isBanned(user) is always false. Here allowLogin never runs at all, and the branch logic is wrong in every case. Fix: isBanned(user).then(banned => { if (!banned) allowLogin(user); }).catch(err => console.error(err)); or use const banned = await isBanned(user); inside an async function.