Is JavaScript async/await implemented with generators? Starting with yield and Promises

January 14, 2025

The request is out and the server has not answered. What is JavaScript doing?

const response = await fetch("/user");
const user = await response.json();

Suppose these lines are inside an async function on a page, and the server will return a user profile for /user. The first line calls fetch() to send a request and immediately receives a Promise. Think of it as “this request will eventually have a result, or it may fail.” await pauses the current function on that line. When the response headers arrive, the function resumes and response receives the response object. The browser can still handle clicks while waiting.1

Why wait a second time? When the headers arrive, the profile may still be in transit. response.json() reads the body to completion and parses the JSON into a JavaScript value. If the body is {"name":"小林"}, user.name yields “小林” after the second await. If the network request fails or the body cannot be parsed, the corresponding await throws an error that try/catch can handle.2

Early JavaScript commonly used callbacks to say what should happen when something finished. A callback is a function handed off for someone else to invoke later. To fetch a user and then fetch articles using the user ID, code starting the second query often lived inside the first query’s callback. Promises give callers a different form: each step returns a result the next step can use. Rewrite the opening lines using Promises to see the connection.32

fetch("/user")
  .then(response => response.json())
  .then(user => console.log(user.name))
  .catch(error => console.error(error));

The first .then() runs once the response arrives. Its arrow function returns the Promise from response.json(), so the next .then() waits for the body and receives the profile. Errors from either step can go to the final .catch(). The opening await form preserves the same order, while letting you assign each result directly to a variable.

ES2015 standardized both Promises and generators. The example above shows how a Promise represents a request’s outcome. To understand generators, start with a problem that needs no network.4

When reading a file line by line, who remembers where we stopped?

Suppose we want the first error in a long log. A reader function can deliver each line to its caller, then pause within its loop. The caller checks the line: if it is an error, stop looking. Otherwise, let the function continue. The line number is still there and the loop remembers where it stopped. A generator lets one function call deliver values in stages and resume from its last suspension point each time. The Python generator proposal illustrated this by reading the tokens of a program one by one. C#’s yield return expresses the same process.5

How does this relate to design patterns? From the caller’s perspective, repeatedly asking for “the next item” lets it iterate through a log while someone else handles the file-reading details. That design is the Iterator pattern. On the implementation side, you could track line numbers and read progress yourself or write a generator loop and let the language retain local variables and the pause point. A generator is a convenient way to implement an iterator.5

Back in JavaScript, replace “yield a log line” with “yield a Promise”. Now we have the next question: when the request finishes, who tells the generator to continue?

Are generators the underlying implementation of async/await?

Not necessarily. A generator combined with Promises can behave like async/await, and Babel has a plugin that really does transform code this way. The JavaScript standard specifies the behavior of await. Engines can choose how to implement it.67

Suppose getUser() returns a Promise. To keep this example runnable, Promise.resolve wraps a ready-made profile. Notice what each .next() does.

function getUser() {
  return Promise.resolve({ name: "小林" });
}

function* showUser() {
  const user = yield getUser();
  console.log(user.name);
}

const task = showUser();
const request = task.next().value;
request.then(user => task.next(user));
  1. Pause first. The star in function* denotes a generator. Calling showUser() produces task, but the body has not started executing. The first task.next() runs it to yield, handing out the Promise returned by getUser(). .value extracts that Promise. The user variable inside the function is still unassigned.
  2. Send the result back. request.then(...) specifies what to do after receiving the profile. Once it arrives, task.next(user) sends it back to the paused yield. Only then is const user = … assigned, and the next line prints “小林”. Remove the last line and run it again: even if the Promise has a result, no name is printed.

The early co library automated the work the example does manually. Version 4.0, released in November 2014 before the final ES2015 standard, already wrapped a generator workflow in a Promise. When yield handed it a Promise, co waited for success and called .next(result), or called .throw(error) to send a failure back to the suspension point. Developers could write queries in execution order, while callers gained access to the final result of the whole workflow.89

ES2017 added the opening async/await syntax to the language. Replace function* with async function and yield getUser() with await getUser(), then simply call showUser(). This time JavaScript arranges when the function resumes. The caller receives a Promise and can continue with .then().7

ES2018 later allowed both syntaxes within the same function. Imagine an async function* reading articles page by page: await waits for the next page and yield delivers one article to the reader. Outside, for await...of reads them one by one. Waiting for data and handing out one item at a time are separate jobs, each with its own keyword.10

How does yieldable-json process large JSON on one thread while letting other requests get responses?

Now move to the server. Suppose Node.js is converting many articles to JSON when someone sends a small request. If the same JavaScript thread stays busy converting articles, the small request’s handler can only wait. The time-consuming part is active CPU computation.

Read await JSON.stringify(posts) carefully. JavaScript first calls JSON.stringify(posts) and converts the entire object to a string. Only then is there a value for await. Likewise await JSON.parse(text) must parse the whole input first. When the computation is large, the slow step happens before execution reaches await.

Ngend Lio raised this in a Q&A about asynchronous JSON parsing: “The JSON.parse is in the main thread and does block the event loop.” The event loop schedules which task runs next. As long as parsing holds control, queued tasks must wait.11

yieldable-json is a Node.js library that processes JSON in chunks on a single JavaScript thread. It provides stringifyAsync to encode a value as JSON text and parseAsync to decode text into a value. Its approach is to do only part of the work on the same thread, remember progress, and leave the next part until later. In the encoder, for example, a generator traverses an object and periodically yields. The surrounding function uses Node.js setImmediate to arrange a later .next(). Think of decoding similarly: read some text, remember the position and partial object, and continue from there next time. Between chunks Node.js can handle ready requests. That is what “nonblocking” means here.12

Below is the algorithm reduced to encoding three numbers, one per step. Run this snippet by itself in Node.js to see where another task fits in. It is a teaching example of execution order.12

function* encodeNumbers(numbers) {
  const parts = []
  for (const number of numbers) {
    parts.push(JSON.stringify(number))
    console.log("已编码", number)
    yield
  }
  return "[" + parts.join(",") + "]"
}

const encoder = encodeNumbers([10, 20, 30])
function step() {
  const result = encoder.next()
  if (result.done) {
    console.log("完成", result.value)
  } else {
    setImmediate(step)
  }
}

setImmediate(() => console.log("处理另一件事"))
step()

It prints “已编码 10” (encoded 10), then “处理另一件事” (handle another task), then 20, 30, and the final [10,20,30]. Try replacing setImmediate(step) with a direct step() call: all three numbers and the complete result print first. Both experiments use yield. The difference is when the outer code returns for the next step.

The real JSON library yields after a stretch of traversal or scanning and delivers the complete result in a callback. Every chunk still takes CPU time, and pausing and resuming add overhead. Only one JavaScript thread performs this computation from start to finish. Chunking gives small requests a chance to receive earlier responses, while the whole JSON operation may even take longer. To tell whether this approach helped, ask both how long the large JSON took to process and how long a small request arriving in the middle had to wait.12

Footnotes

  1. MDN contributors. (n.d.). Using the Fetch API. MDN Web Docs. Handling the response. ↩

  2. Hughes, N. (2023, June 28). Async Await vs Fetch.Then(). DEV Community. Fetch example. ↩ ↩2

  3. V8 team. (2018, November 12). Faster async functions and promises. V8 Blog. From callbacks to promises to async functions. ↩

  4. Ecma International. (2015, June). ECMAScript 2015 language specification (6th ed.). §14.4 Generator function definitions, §25.4 Promise objects. ↩

  5. Schemenauer, N., Peters, T., & Hetland, M. L. (2001, May 18). PEP 255 – Simple generators. Python Enhancement Proposals. Motivation: yielding tokens one by one and retaining traversal progress. Microsoft. (n.d.). yield statement. Microsoft Learn. Pausing and resuming a C# iterator. ↩ ↩2

  6. Babel contributors. (n.d.). @babel/plugin-transform-async-to-generator. Babel. Example: code before and after transformation. ↩

  7. Ecma International. (2017, June). ECMAScript 2017 language specification (8th ed.). §14.6 Async function definitions, and the current specification’s definition of Await. ↩ ↩2

  8. co contributors. (2014, November 15). History: 4.0.0. GitHub. 4.0.0 changelog. ↩

  9. co contributors. (n.d.). co: Generator based flow-control for Node.js. GitHub. Functions handling fulfillment, rejection, and advancement in index.js. ↩

  10. Ecma International. (2018, June). ECMAScript 2018 language specification (9th ed.). Async generator function definitions. ↩

  11. Ngend Lio. (2017, October 9). How to parse or Stringify in asycnhronous way in javascript. Stack Overflow. Question and author’s reply to Utkarsh Dubey, 12:44 UTC. ↩

  12. IBM Runtimes contributors. (n.d.). yieldable-json. GitHub. Background: incremental parsing and encoding design, Where the encoder pauses traversal, Resuming traversal with setImmediate and delivering the result. ↩ ↩2 ↩3

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-01-14). Is JavaScript async/await implemented with generators? Starting with yield and Promises. https://caiborui.com/blog/2025-01-14-zh-generator-promise-and-async-await-entrans

@misc{borui2025-dd167f57,
  author = {borui},
  title = {{Is JavaScript async/await implemented with generators? Starting with yield and Promises}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-01-14-zh-generator-promise-and-async-await-entrans}
}