Introducing Promise.try(): A Super‑Useful ES2025 API for Cleaner Async Code
Promise.try(), added in ES2025, is a static method that wraps any function—sync or async—into a Promise, automatically captures synchronous errors, and provides a unified, concise API for handling both synchronous and asynchronous operations, as demonstrated through multiple code examples and practical scenarios.
What is Promise.try()?
Promise.try() is a static method that can wrap any function—whether synchronous, asynchronous, returning a value, or throwing an exception—into a Promise. It handles both sync and async functions uniformly and automatically captures synchronous errors.
Syntax
Promise.try(func)
Promise.try(func, arg1)
Promise.try(func, arg1, arg2)
Promise.try(func, arg1, arg2, /* … */ argN)Parameters
func: the function to wrap; can be sync or async. arg1, arg2, … argN: arguments passed to func.
Return value
A Promise whose state depends on func:
If func returns a value synchronously, the Promise is fulfilled.
If func throws synchronously, the Promise is rejected.
If func returns a Promise, the resulting Promise adopts that state.
Why need Promise.try()?
In real development we often encounter situations where we do not want to distinguish whether a function is sync or async but still want to handle it with a Promise. Previously we might use Promise.resolve().then(f), which forces a synchronous function to execute asynchronously.
const f = () => console.log('now');
Promise.resolve().then(f);
console.log('next');
// next
// nowThe example shows that the synchronous function becomes asynchronous. Promise.try() allows synchronous functions to stay synchronous while still providing a unified API.
How to use Promise.try()
Example 1: handling a synchronous function
const syncFunction = () => {
console.log('同步函数执行中');
return '同步的结果';
};
Promise.try(syncFunction)
.then(result => console.log(result)) // 输出:同步的结果
.catch(error => console.error(error));Example 2: handling an asynchronous function
const asyncFunction = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve('异步的结果');
}, 1000);
});
};
Promise.try(asyncFunction)
.then(result => console.log(result)) // 1秒后输出:异步的结果
.catch(error => console.error(error));Example 3: handling a function that may throw
const errorFunction = () => {
throw new Error('同步的错误');
};
Promise.try(errorFunction)
.then(result => console.log(result))
.catch(error => console.error(error.message)); // 输出:同步的错误Advantages of Promise.try()
Unified handling of synchronous and asynchronous functions; code becomes cleaner.
Automatic capture of synchronous exceptions, making error handling more straightforward.
More concise and readable compared with traditional patterns.
Practical scenarios
Scenario 1: unified API request handling
function fetchData(url) {
return Promise.try(() => fetch(url))
.then(response => response.json())
.catch(error => console.error('请求失败:', error));
}
fetchData('https://api.example.com/data')
.then(data => console.log('数据:', data));Scenario 2: mixing sync and async operations
const syncTask = () => '同步任务完成';
const asyncTask = () => new Promise(resolve => setTimeout(() => resolve('异步任务完成'), 1000));
Promise.try(syncTask)
.then(result => console.log(result)) // 同步任务完成
.then(() => Promise.try(asyncTask))
.then(result => console.log(result)) // 1秒后输出:异步任务完成
.catch(error => console.error(error));Scenario 3: database query handling
function getUser(userId) {
return Promise.try(() => database.users.get({ id: userId }))
.then(user => user.name)
.catch(error => console.error('数据库查询失败:', error));
}
getUser('123')
.then(name => console.log('用户名称:', name));Scenario 4: file reading
function readFile(path) {
return Promise.try(() => fs.readFileSync(path, 'utf8'))
.catch(error => console.error('文件读取失败:', error));
}
readFile('example.txt')
.then(content => console.log('文件内容:', content));Conclusion
Promise.try() introduced in ES2025 simplifies asynchronous programming by unifying the handling of synchronous and asynchronous functions and improving error handling, resulting in clearer and more maintainable code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Cultivation Path
Focused on sharing practical tech content about TypeScript, Vue 3, front-end architecture, and source code analysis.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
