Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Created March 2, 2022 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coolaj86/36811338a0cd3a047258b1bd4d5fe128 to your computer and use it in GitHub Desktop.
Save coolaj86/36811338a0cd3a047258b1bd4d5fe128 to your computer and use it in GitHub Desktop.

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