为什么前端开发者都不用 try-catch 了?


JavaScript 正为 Promise 添加一个新的方法,使得处理异步函数更加清晰和安全。Promise.try 允许将任何函数包装在 Promise
中,无论它是否异步。

核心问题:

try-catch 主要用于同步代码块,它可以捕获在 try 块中抛出的同步错误。

try {  
    // 同步代码  
    throw new Error("Sync error");  
} catch (e) {  
    console.error(e.message); // 捕获到错误  
}  

但对于在 try 块中调用了异步操作(如 setTimeoutPromise 等),那么异步操作中的错误不会被同一 try-catch 语句捕获,因为它们是在事件循环的下一个周期中执行的。

function asyncFunction() {  
    return new Promise((resolve, reject) => {  
        try {  
            setTimeout(() => {  
                throw new Error("Async error");  
            }, 1000);  
        } catch (e) {  
            console.error(e.message); // 不会捕获到错误  
            reject(e);  
        }  
    });  
}  

在这个例子中, try/catch 实际上是多余的,因为异步操作中的错误不会被 try/catch 捕获。

这使得在处理异步操作时,我们不得不在每个可能抛出错误的地方都添加 try-catch 块,这不仅增加了代码的复杂度,而且容易导致错误的遗漏:

function asyncFunction() {  
    return new Promise((resolve, reject) => {  
        try {  
            setTimeout(() => {  
              try {  
                throw new Error("Async error");  
              } catch (e) {  
                console.error('FedJavaScript', e.message); // 捕获到错误  
                reject(e)  
              }  
            }, 1000);  
        } catch (e) {  
            console.error(e.message); // 不会捕获到错误  
            reject(e);  
        }  
    });  
}  

这代码很不优雅!

解决方案: Promise.try

Promise.try 为我们提供了一种处理该情况的简洁方法:

Promise.try(() => {  
    // 同步代码  
    throw new Error("Sync error");  
}).catch(e => {  
    console.error(e.message); // 捕获到错误  
});  
  
Promise.try(() => {  
    // 异步代码  
    return new Promise((resolve, reject) => {  
        setTimeout(() => {  
            throw new Error("Async error");  
        }, 1000);  
    });  
}).catch(e => {  
    console.error(e.message); // 捕获到错误  
});  

允许我们以更一致的方式处理异步操作的错误,尤其是在使用 Promises 时。

Promise.try 的优点:

  1. 简洁性 : Promise.try 让我们可以直接在一个函数中处理同步操作,而无需额外的 new Promise 包装或 try...catch

  2. 一致性 :无论是同步还是异步操作,使用相同的错误处理机制可以减少代码风格的不一致,使整个项目更加统一

  3. 易用性 :对于初学者来说,理解 Promise.try 比学习如何正确地组合 new Promisetry...catch 更加直观

参考:https://tc39.es/ecma262/#sec-promise.try