Vanta Logo
SPONSOR
Automate SOC 2 & ISO 27001 compliance with Vanta. Get $1,000 off.
Published
3 min read
Up to date

Trevor I. Lasn

Staff Software Engineer, Engineering Manager

Promise.try: Unified Error Handling for Sync and Async JavaScript Code (ES2025)

Stop mixing try/catch with Promise chains - JavaScript's new Promise.try handles return values, Promises, and errors uniformly

JavaScript is getting a new Promise utility that makes handling potentially async functions cleaner and safer. Promise.try lets you wrap any function in a Promise, whether it’s async or not, while maintaining optimal execution timing.

The Core Problem

Handling functions that might be sync or async requires mixing different error handling patterns:

JavaScript
function getUserData(id) {
// We need try/catch for sync errors
try {
validateId(id);
// Might return cached data synchronously
if (id in cache) {
return cache[id];
}
// Might return a Promise
return fetch(`/api/users/${id}`);
} catch (syncError) {
handleSyncError(syncError);
}
}

The problem? You never know which behavior you’ll get. Currently, there are two common ways to handle this, but neither is ideal:

JavaScript
// Method 1: Using Promise.resolve().then()
Promise.resolve().then(() => getUserData(123));
// ❌ Forces everything to be async
// ❌ Even cached data waits for the next tick
// ✓ But at least it catches errors
// Method 2: Using new Promise
new Promise(resolve => resolve(getUserData(123)));
// ❌ Verbose and clunky
// ❌ Easy to get wrong
// ✓ Runs sync code immediately

We need a better way to:

  • Run synchronous code immediately (for better performance)
  • Handle asynchronous code when needed
  • Catch any errors that might occur
  • Do all this with clean, readable syntax

The Solution: Promise.try

Promise.try gives us one clean way to handle all cases:

JavaScript
// Clean, safe, and optimal timing
Promise.try(() => getUserData(123))
.then(user => {
// Gets called with:
// - Immediate values (from cache)
// - Resolved Promise values (from fetch)
})
.catch(error => {
// Catches both:
// - Synchronous throws
// - Promise rejections
});

Why It’s Better

Promise.try has three key advantages:

JavaScript
// 1. Runs synchronously when possible
Promise.try(() => "instant") // Executes immediately
.then(x => console.log(x));
// 2. Catches all errors reliably
Promise.try(() => {
throw new Error('boom');
})
.catch(err => console.log('Caught:', err));
// 3. Handles both sync and async naturally
Promise.try(() => {
if (Math.random() > 0.5) {
return "sync value";
}
return fetch('/api/data');
});

Promise.try runs synchronous code immediately for better performance, while still handling async operations when needed. It catches every type of error through a single catch handler, and does it all with clean, readable syntax. Think of it as the Promise equivalent of a try-catch block - a safe way to execute code that might fail or might be async, without having to know which it is ahead of time.

This is particularly powerful when working with functions that might change their behavior over time. Your error handling remains consistent whether the function returns immediately or needs to make an API call. No more wrapping everything in try-catch blocks and then also handling Promise rejections separately.

References

If you found this article helpful, you might enjoy my free newsletter. I share developer tips and insights to help you grow your skills and career.


More Articles You Might Enjoy

If you enjoyed this article, you might find these related pieces interesting as well. If you like what I have to say, please check out the sponsors who are supporting me. Much appreciated!

Javascript
5 min read

Working with JavaScript's Scheduler API

Learn how to prioritize and control task execution in JavaScript using the new Scheduler API for better performance and user experience

Nov 26, 2024
Read article
Javascript
4 min read

Embrace Intermediate Variables and Early Returns in JavaScript

Early returns and intermediate variables make your code easier to reason about

Aug 30, 2024
Read article
Javascript
3 min read

JavaScript's &&= Operator: Understanding Logical AND Assignment

Use the &&= operator to safely update truthy values while preserving falsy states

Nov 5, 2024
Read article
Javascript
4 min read

Intl.DurationFormat: Format Time Durations with Locale Support

Stop writing manual duration formatting code. Instead, leverage the new powerful Intl.DateTimeFormat API for internationalized time displays

Mar 13, 2025
Read article
Javascript
4 min read

Understanding Bitwise Shifts in JavaScript: << and >>

A practical guide to left and right shift operators in JavaScript

Nov 12, 2024
Read article
Javascript
3 min read

navigator.clipboard - The New Asynchronous Clipboard API in JavaScript

Copy and paste text, images, and files using the new navigator.clipboard API

Dec 7, 2024
Read article
Javascript
7 min read

WeakRefs in JavaScript: Explained In Simple Terms

Understanding how WeakRef helps manage memory in JavaScript

Jan 7, 2025
Read article
Javascript
7 min read

JavaScript Operators: '||' vs '&&' vs '??'

Master JavaScript logical operators with practical examples and best practices

Oct 26, 2024
Read article
Javascript
7 min read

What's New in Express.js v5.0

A detailed look at the key changes and improvements in Express v5.0 and how to migrate your app

Sep 16, 2024
Read article

Become a better engineer

Here are engineering resources I've personally vetted and use. They focus on skills you'll actually need to build and scale real projects - the kind of experience that gets you hired or promoted.

Many companies have a fixed annual stipend per engineer (e.g. $2,000) for use towards learning resources. If your company offers this stipend, you can forward them your invoices directly for reimbursement. By using my affiliate links, you support my work and get a discount at the same!


This article was originally published on https://www.trevorlasn.com/blog/promise-try-in-javascript. It was written by a human and polished using grammar tools for clarity.