Sub topic 4
Async Functions Always Return a Promise
This chapter assumes you can create and chain Promises with then and catch, and that you are comfortable with regular and arrow functions. Here we look at what the async keyword does to a function before you use await inside it.
The async keyword changes the return type
Putting async before a function guarantees that calling it returns a Promise. That holds whatever the body returns.
async function getNumber() {
return 42;
}
console.log(getNumber() instanceof Promise); // true
getNumber().then(value => console.log(value)); // 42The body says return 42, but the caller receives a Promise that fulfills with 42. To get the number out, you need then or await.
The keyword works with every function form:
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'; }
}
Promise.all([
declared(),
expressed(),
arrow(),
obj.method(),
new Service().load()
]).then(values => console.log(values));
// ['declaration', 'expression', 'arrow', 'method', 'class method']Three rules for the returned Promise
What the body does decides how the returned Promise settles.
| Body does | Returned Promise |
|---|---|
| Returns a plain value (or nothing) | Fulfills with that value (or `undefined`) |
| Throws an error | Rejects with that error |
| Returns a Promise | Adopts it and settles the same way |
Throwing becomes rejection
A throw inside an async function does not escape synchronously to the caller. It turns into a rejected Promise.
async function failNow() {
throw new Error('boom');
}
try {
failNow();
console.log('no synchronous error was thrown');
} catch (err) {
console.log('never runs');
}
failNow().catch(err => console.log('caught:', err.message)); // caught: boomThe try/catch around the bare call catches nothing, because the call itself succeeds and returns a rejected Promise. Handling that rejection is the subject of a later chapter.
Returned Promises are not double-wrapped
If you return a Promise, you do not get a Promise of a Promise. The outer Promise adopts the inner one's result.
async function passThrough() {
return Promise.resolve('inner value');
}
passThrough().then(value => {
console.log(value); // 'inner value', not a Promise
});The body starts running immediately
Calling an async function does not defer its body. The code runs synchronously up to the first await, or to the end if there is none. Only the settlement of the returned Promise is delivered later.
async function report() {
console.log('2: inside the body');
return 'result';
}
console.log('1: before call');
report().then(value => console.log('4:', value));
console.log('3: after call');
// 1: before call
// 2: inside the body
// 3: after call
// 4: resultEven though the Promise is already fulfilled when report returns, the then callback waits until the current synchronous code finishes.
Common errors
- Treating the result as a value.
const n = getNumber(); n + 1gives"[object Promise]1", not43. Usethenorawait. - Expecting synchronous exceptions. Errors thrown inside an async function come back as rejections. Unhandled ones show up as "unhandled promise rejection" warnings.
- Adding
asyncwithout a reason. Marking a functionasyncchanges its contract for every caller. If it has noawaitand its callers expect a plain value, leave the keyword off. - Wrapping manually.
return Promise.resolve(x)inside an async function does nothing thatreturn xdoesn't already do.
Exercise
What does this code print, and in what order? async function f() { console.log('a'); throw new Error('b'); } f().catch(e => console.log(e.message)); console.log('c');
Show answer
It prints a, then c, then b. The body runs synchronously and logs a, and the throw turns into a rejected Promise instead of escaping. The script then logs c, and the catch callback logs b after the synchronous code finishes.
Exercise
An async function getConfig ends with return fetchConfigPromise;, where fetchConfigPromise eventually fulfills with { debug: true }. What value does getConfig().then(v => console.log(v)) log?
Show answer
It logs { debug: true }. The async function's Promise adopts the returned Promise, so it is not double-wrapped and v is the plain object.