try和finally的return问题

2018-10-04

先来看一个代码片段

1
2
3
4
5
try{
return true;
}finally{
return false;
}

问最后的结果是true还是false,答案是false。下面改造一下代码片段,来看一下整个顺序流程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const num = 0;

tryReturn = () => {
console.log('我是try return');
++num;
console.log(num);
return ++num;
}

finallyReturn = () =>{
console.log('我是finally return');
return ++num;
}

test = () => {
try{
console.log('我是try块');
return tryReturn();
}finally{
console.log('我是finally块');
return finallyReturn();
}
}