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:
The problem? You never know which behavior you’ll get. Currently, there are two common ways to handle this, but neither is ideal:
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:
Why It’s Better
Promise.try
has three key advantages:
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.