DEV Community

Cover image for Stop Nesting Try/Catch: How I Turned a Repetitive Pattern into an NPM Package (promise-tuple)
Eduardo Donato
Eduardo Donato

Posted on

Stop Nesting Try/Catch: How I Turned a Repetitive Pattern into an NPM Package (promise-tuple)

Recently, I noticed that in almost every project, I was writing the same utility to handle Promises. I decided it was time to stop copy-pasting code and published a npm package: promise-tuple.

The Motivation

You know those times when you need to run several asynchronous calls in sequence, but each one requires specific error handling? The traditional try/catch pattern often results in "staircase code" or multiple variables declared with let outside the block just so they can be accessed later.

Example of the "problem":

let user;
try {
  user = await fetchUser();
} catch (err) {
  return handleUserError(err);
}

let posts;
try {
  posts = await fetchPosts(user.id);
} catch (err) {
  return handlePostError(err);
}

Enter fullscreen mode Exit fullscreen mode

The Solution: The Tuple Pattern

Inspired by languages like Go, the idea is to always return a tuple (a fixed array) containing [data, error]. If an error occurs, it’s populated; otherwise, you have your data.

Using promise-tuple, the code above looks like this:

import promiseTuple from 'promise-tuple';

const [user, userErr] = await promiseTuple(fetchUser());
if (userErr) return handleUserError(userErr);

const [posts, postsErr] = await promiseTuple(fetchPosts(user.id));
if (postsErr) return handlePostError(postsErr);

Enter fullscreen mode Exit fullscreen mode

Why use it?

  • Readability: The error flow is explicit and sits right next to the function call.
  • Native TypeScript: The package was built with type inference in mind, so both data and error are correctly typed.
  • Minimalist: Zero external dependencies and extremely lightweight.

Final Thoughts

I know there are other libraries that do similar things, but building my own allowed me to tailor it exactly to my needs and, in the process, give back to the community.

Check it out here: https://www.npmjs.com/package/promise-tuple

Top comments (0)