Promise.try()
Promise.try() wraps synchronous or asynchronous logic into a Promise-based flow. It is useful when you want a consistent error-handling path without writing separate try/catch wrappers.
Overview
Promise.try() wraps synchronous or asynchronous logic into a Promise-based flow. It is useful when you want a consistent error-handling path without writing separate try/catch wrappers.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 128 | 128 | 134 | 18.2 | 128 | 18.2 | |
Syntax
// Both synchronous and asynchronous functions are acceptable
Promise.try(() => {
if (cached) return cachedValue; // Return synchronously
return fetch('/api/data'); // Return a Promise
}).then(result => console.log(result)); Live demo
Start a chain from Promise.try
Use Promise.try when available, otherwise fall back to Promise.resolve().then().
Capture sync exceptions
Normalize thrown synchronous errors into a rejected promise chain.
Mix sync and async steps
Start from sync setup and continue into asynchronous work without branching.
Use cases
Unified execution wrappers
Treat a callback the same way whether it returns a value immediately or eventually resolves.
Centralized failure handling
Route thrown errors and rejected promises through one Promise chain.
Cautions
- Do not wrap everything reflexively; clearer direct async code is often easier to read.
- Promise utilities should still preserve meaningful stack traces and explicit control flow.
Accessibility
- Reliable async error handling helps ensure users receive consistent feedback when something fails.
- Promise normalization is only useful if resulting errors are surfaced in accessible UI.
Related links
Powered by web-features