Chained callback pattern in Javascript

Imagine we have four methods a(next), b(next), c(next), d() where the first three accept a callback. We want to execut these methods in order, so that a completes and calls b, b completes and calls c, and c completes and calls d.

In plain-old Javascript this might look like:

a(function() {  
  b(function() {
    c(function() {

Clearly the callback pyramid of doom is in effect. Additionally, there is no extensibility, as in you can't add additional methods without continuing the callback pyramid of doom.

Fortunately, you can do this quite easily with a chain method. To implement a chain method, function calls get stored in an array. The first position is plucked off the array and supplied to the chain function. The chain function is recursively called with the next element in the array. This ends up looking like this:

let fns = [a,b,c,d];

// chain function will call the supplied function
// and recursively call the chain function with the
// the next element in the array
function chain(fn) {  
  if(fn) {
    fn(() => chain(fns.shift()));

// start the chain with the first element in the array

That's all there is to it! To view a working example visit:

comments powered by Disqus