Published: January 17, 2025
Doing asynchronous work on the web can be challenging—and a lot of what's done on the web involves asynchronicity. Whether that involves fetch
calls or other asynchronous operations, how you do that work is made easier by browsers when built-in methods provide robust error handling. This has already been provided for Promises using the then
, catch
, and finally
methods.
Even so, the way in which you architect your application's codebase should be flexible, and not everything you'll do in your application is necessarily asynchronous. Sometimes you might want to handle the result of a callback in a way that would be simpler if it didn't matter whether a callback you passed to a Promise
is synchronous or not. Promise.try
is a method now available in all major browser engines that simplifies this for developers, which means that it's now Baseline Newly available.
What is Promise.try
and how does it work?
Promise.try
is a convenience method that makes error handling for synchronous callback functions easier than if you used Promise.resolve
:
// If the callback is synchronous and it throws
// an exception, the error won't be caught here:
new Promise(resolve => resolve(callback());
// But it will be here:
Promise.try(callback);
Then, using the then
, catch
, and finally
methods, handle the resolution or rejection of a Promise
:
Promise.try(callback)
.then(result => console.log(result))
.catch(error => console.log(error))
.finally(() => console.log("All settled."));
What if your callback function has arguments? You can handle this in one of two ways:
// This creates an extra closure, but works:
Promise.try(() => callback(param1, param2));
// This doesn't create an extra closure, and still works:
Promise.try(callback, param1, param2);
The primary benefit of using Promise.try
is that it lets you uniformly use Promises regardless of whether or not the callback you pass to it is synchronous or asynchronous. This means that, in the case of a utility function that passes callbacks to a Promise
that's widely used in your code, using Promise.try
ensures proper error handling for any callback you pass to it. For additional information and other potential concerns or use cases, consult the MDN documentation for Promise.try
.
Conclusion
Now that Promise.try
has reached Baseline Newly available, you should be able to use it in all major browser engines. As time passes, you should expect to be able to use Promise.try
in your web applications with increasing confidence that it will be a stable and interoperable part of the web platform.