Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Pyramids of Doom in JavaScript

  • callbacks
  • promises
  • try/catch

solution: await.catch

async function doLotsOfStuff(params) {
  var result = await doStuff(params.foo, params.bar);
  var result2 doMoreStuff().catch(function (err) {
    if ('FIX_ME' === err.code) {
      return { fixed: true };
    }
    throw err;
  });
  var result3 = await doEvenMoreStuff(params.baz);
  return result3;
}

Callback Pyramid of Doom

function doLotsOfStuff(params, cb) {
  doStuff(params.foo, params.bar, function (err1, result) {
    doMoreStuff(function (err2, result) {
      if (err2) {
        cb(err2)
        return;
      }
      doEvenMoreStuff(params.baz, function (err3, result) {
        // callback pyramid of doom
      });
    });
  });
}

Promises Pyramid of Doom

function doLotsOfStuff(params) {
  return doStuff(params.foo, params.bar).then(function (result) {
    return doMoreStuff().then(function (result) {
      return doEvenMoreStuff(params.baz).then(function (result) {
        // promises pyramid of doom
        return result;
      });
    }).catch(function (err) {
      if ('FIX_ME' === err.code) {
        return { fixed: true };
      }
      throw err;
    });
  });
}

try/catch Pyramid of Doom

async function doLotsOfStuff(params) {
  try {
    var result = await doStuff(params.foo, params.bar);
    try {
      var result = await doMoreStuff();
      try {
        var result = await doEvenMoreStuff(params.baz).then(function (result) {
        // try/catch pyramid of doom
        return result;
      } catch(e) {
        throw err;
      }
    } catch(e) {
      if ('FIX_ME' === err.code) {
        return { fixed: true };
      }
      throw err;
    }
  } catch(e) {
    throw err;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment