A new Baseline Promise helper

Handling asynchronous work is a core part of web development, and browsers have steadily improved the ergonomics of that work. The then, catch, and finally methods on Promises already give you a solid toolkit for robust error handling. But for cases where you are not sure whether a function will run synchronously or return a Promise, plumbing can get awkward. The Promise.try method, now Baseline Newly available across all major browser engines, addresses that gap.

What Promise.try offers

Promise.try is a convenience method that simplifies error handling for Synchronous callback functions. It is a more direct option than relying on Promise.resolve to normalize a value or a thrown error into a Promise:

// 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);

Once wrapped, you can use the standard then, catch, and finally methods to manage the resolution or rejection of the resulting Promise:

Promise.try(callback)
  .then(result => console.log(result))
  .catch(error => console.log(error))
  .finally(() => console.log("All settled."));

For callbacks that need arguments, you have two clean patterns available:

// 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 core advantage of Promise.try is uniformity. When you use it, the code handling the outcome does not need to care if the function you pass in is synchronous or asynchronous. This is particularly valuable in utility functions that are shared across a codebase and accept a variety of callbacks. By wrapping callbacks with Promise.try, you ensure that any synchronous exceptions are caught and routed through the same error-handling paths as asynchronous rejections, preventing uncaught errors. For more details and potential edge cases, see the MDN documentation for Promise.try.

Availability and outlook

With this feature reaching Baseline Newly available, you can rely on Promise.try being supported in all major browser engines. As the web platform continues to converge on this standard, you can adopt it with greater confidence in its stability and interoperability for your applications.