All sample questions / JavaScript

What does .then(v => console.log(v)) print? JavaScript Promises, async await and the Event Loop

Block 6, Promises, async await and the Event Loop, question 3 of the JavaScript sample

Promise.resolve(1)
  .then(async v => {
    await null;
    return v + 1;
  })
  .then(v => console.log(v));

What does this print?

  1. A. 2
  2. B. 1
  3. C. [object Promise]
  4. D. undefined
Show the answer and why each option is right or wrong

Answer, A. 2

A. 2
Correct. An async function used as a then handler still returns a promise, which the chain automatically adopts before continuing.
B. 1
Assumes the handler returns its input unchanged because the addition happens after an await inside it. The handler still computes and returns the incremented value once its internal await resumes.
C. [object Promise]
Assumes returning from an async then handler leaves the chain holding an unresolved promise instead of a plain number. Then always waits for a promise returned by a handler to settle before passing its value onward.
D. undefined
Assumes using an async function as a then handler prevents the chain from ever continuing at all. The chain continues normally, it simply waits one extra microtask tick for the async handler to finish.

A then handler can be an async function without anything special happening beyond the fact that it, like every async function, returns a promise. The chain treats that returned promise exactly as it would any other returned promise, waiting for it to settle before handing its value to the next handler.

The answer above is what the Node interpreter printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 600 JavaScript interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 600 JavaScript questions, 9 euros

Or play the free JavaScript sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.