Promise.try for Unified Sync and Async Error Handling
Briefly

Promise.try for Unified Sync and Async Error Handling
"Promise.try, part of the ECMAScript 2026 standard and already available in modern engines, solves this. It gives us a single way to call sync/async code with consistent error handling no more awkward wrappers like Promise.resolve().then(fn) or verbose new Promise(...). Promise.try executes the callback synchronously, then: Wraps its return value (whether sync or a promise) in a Promise Converts synchronous throw into a rejected Promise Avoids the extra async hop added by .then() Signature: Promise.try(fn, ...args) // returns a Promise You can also pass arguments directly, reducing the need for extra lambdas."
"Mixing sync and async functions often leads to inconsistent error handling. Some code requires try/catch, others .catch(), and exceptions sometimes leak unnoticed. function executeTask(action, input) { try { const possible = action(input); return Promise.resolve(possible).catch(err => { logIssue(err); throw err; }); } catch (err) { logIssue(err); return Promise.reject(err); } } Messy and duplicated. function executeTask(action, input) { return Promise .try(action, input) .catch(err => { logIssue(err); throw err; }); } Cleaner, predictable, and unified."
Promise.try executes a callback synchronously and returns a Promise that wraps the callback’s return value or the returned Promise. Synchronous throws are converted into rejected Promises and Promise.try avoids the extra asynchronous hop introduced by .then(). The signature Promise.try(fn, ...args) allows passing arguments directly, reducing the need for extra lambdas. Using Promise.try eliminates duplicated try/catch and Promise.resolve wrappers, providing consistent error handling across sync and async functions. Helper patterns such as asPromise(() => ...) and simplified executeTask implementations benefit from this unified approach.
Read at jsdevspace.substack.com
Unable to calculate read time
[
|
]