Promise.try()
The Promise.try() static method takes a callback of any kind (returns or throws, synchronously or asynchronously) and wraps its result in a Promise.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 128 | 128 | 134 | 18.2 | 128 | 18.2 | |
1+Supported (version) Not supported ※Has note Sub-feature descriptions sourced from MDN Web Docs (CC BY-SA 2.5)
Syntax
JAVASCRIPT
// 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().
JavaScript
Output
Press the Run button
Capture sync exceptions
Normalize thrown synchronous errors into a rejected promise chain.
JavaScript
Output
Press the Run button
Mix sync and async steps
Start from sync setup and continue into asynchronous work without branching.
JavaScript
Output
Press the Run button
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.