atk*_*yla 3 javascript promise ecmascript-6 es6-promise
我偶然发现了一些我不喜欢的代码:
try {
somePromise()
.then(res => console.log(res));
} catch (err) {
console.error(err);
}
Run Code Online (Sandbox Code Playgroud)
如果某些操作somePromise()
失败,将不会被捕获,并且应用程序将崩溃?这个try-catch甚至还能做什么?
应该是这样吗?:
somePromise()
.then(res => console.log(res))
.catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)
TL; DR-如果返回诺言的函数在返回诺言之前引发异常,则必须在常规try-catch块中捕获该异常。
考虑这个功能
function asyncAdd(x,y){
if(x === 2){
throw new Error("good old exception")
}else if(x === 1) {
return Promise.reject("fancy exception")
}
return Promise.resolve(x+y)
}
Run Code Online (Sandbox Code Playgroud)
这将打印“尝试捕获良好的旧异常”
try{
asyncAdd(2,10).then(x =>console.log("result", x)).catch(y => console.error("Promise caught", y));
}catch (e){
console.error("Try caught", e);
}
Run Code Online (Sandbox Code Playgroud)
这将打印“ Promise catched fancy异常”
try{
asyncAdd(1,10).then(x =>console.log("result", x)).catch(y => console.error("Promise caught", y));
}catch (e){
console.error("Try caught", e);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2981 次 |
最近记录: |