MENU
Promise.try()
Promise.try(callbackFn, ...args), added in ECMAScript 2025, calls callbackFn(...args) and wraps the outcome in a Promise no matter what callbackFn turns out to be: synchronous or async, returning a plain value or already returning a Promise, or throwing synchronously. It is the single entry point that replaces having to know in advance whether a function is synchronous before deciding how to safely call it.
Without Promise.try(), calling a possibly-synchronous function that might throw immediately requires its own try...catch, separate from the .catch() used for the async case.
function mightThrowSync(x) {
if (x < 0) throw new RangeError('negative');
return x * 2;
}
// the old, awkward way:
function safeCallOld(fn, x) {
try {
return Promise.resolve(fn(x));
} catch (e) {
return Promise.reject(e);
}
}
// the new way:
function safeCallNew(fn, x) {
return Promise.try(fn, x);
}
safeCallNew(mightThrowSync, -1).catch(e => console.log(e.message));
safeCallNew(mightThrowSync, 5).then(v => console.log(v));negative
10