liveBook · Manning

Asynchronous programming

As explained in Functional Programming in JavaScript

A programming approach in which operations proceed without blocking the current thread while results are delivered later via completion, events, or callbacks.

Asynchronous programming keeps remote work from blocking the current flow, then delivers results through callbacks. It suits progressively loaded data, such as an email inbox, but requires careful control of execution order. section 8.1

Manage three recurring problems:

  • Create an explicit temporal dependency when one function needs data produced by another. section 8.1
  • Avoid deeply nested callbacks, often called a callback pyramid or “Christmas tree of doom.” section 8.1
  • Separate asynchronous work from synchronous loops so callbacks retain the intended current record. section 8.1

Passing the current record

const processStudent = student => { if (student.address.country === 'US') { getJSON(`/students/${student.ssn}/grades`, showStudentsGrades(student), handleError); } }; students.forEach(processStudent); section 8.1

Figure 8.4. Passing the current student object as a parameter properly sets the function’s closure and solves the ambiguity resulting from executing remote calls in a loop.

Passing the current student into the callback establishes the intended closure and removes ambiguity during remote calls in a loop. section 8.1

How Functional Programming in JavaScript covers it

How deep it goes
Explains callbacks, temporal dependencies, nested-call problems, closures, and a continuation-passing refactoring.
Examples
Uses email loading, student records, grades, AJAX requests, XMLHttpRequest, and student-search interface handlers.
What it assumes
Assumes JavaScript functions, loops, callbacks, closures, event handlers, and remote requests.
What you can do after
Diagnose timing and closure bugs, sequence callbacks, and refactor nested asynchronous handlers.
How it connects
Connects callbacks, temporal coupling, closures, continuation-passing style, remote I/O, and synchronous loops.

Also explained in

Compare how 28 books explain asynchronous programming →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.