liveBook · Manning

Nexttick

As explained in Build a Frontend Web Framework (From Scratch)

nextTick is a book-specific asynchronous function that resolves after pending component lifecycle or rendering work has had an opportunity to run.

nextTick() is an asynchronous framework function for testing components. It returns a Promise that resolves after pending scheduler jobs have run, allowing the component to re-render before the test inspects the DOM. section 14.0 section 14.4

Use nextTick() to coordinate tests with asynchronous component work:

  • Mount the component or trigger an asynchronous event. section 14.1
  • Await nextTick() before asserting the updated DOM. section 14.1
  • Await nextTick() before unmounting, and again afterward when unmount hooks are asynchronous. section 14.1.1

Testing asynchronous data loading

A component can initially render “Loading...” while an onMounted() hook fetches todos. After mocking fetch(), await nextTick(), then assert that “Feed the cat” and “Mow the lawn” appear in the DOM. Without awaiting, the loading state remains the immediately observable result. section 14.1.1

Listing 14.1 nextTick() and flushPromises() (scheduler.js)
export function nextTick() {
  scheduleUpdate()
  return flushPromises()
}

function flushPromises() {
  return new Promise((resolve) => setTimeout(resolve))
}

The implementation schedules scheduler processing, then waits through a timer-backed Promise so pending microtasks and jobs can finish before the returned Promise resolves. section 14.1.3

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Explains scheduler microtasks, task queues, and Promise flushing, then implements nextTick() without pursuing production-level completeness.
Examples
Uses counter tests, asynchronous todo loading, mocked fetch calls, cleanup hooks, and a flushPromises() queue-order exercise.
What it assumes
Assumes familiarity with JavaScript event loops, tasks, microtask queues, Promises, components, and asynchronous lifecycle hooks.
What you can do after
Apply it via the framework API to wait for asynchronous hooks or handlers before checking rendered DOM state.
How it connects
Connects component rendering with asynchronous hooks, event handlers, schedulers, the event loop, microtasks, and Promises.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.