mirror of
https://github.com/KieSun/all-of-frontend.git
synced 2024-11-25 16:28:13 +08:00
33 lines
876 B
Markdown
33 lines
876 B
Markdown
|
```js
|
||
|
try {
|
||
|
let a = 0
|
||
|
;(async function() {
|
||
|
a += 1
|
||
|
console.log('inner', a)
|
||
|
throw new Error('123')
|
||
|
// a()
|
||
|
})()
|
||
|
console.log('outer', a)
|
||
|
} catch(e) {
|
||
|
console.warn('Error', e)
|
||
|
}
|
||
|
```
|
||
|
|
||
|
这道题目基础不好的同学容易答错,很容易以为 `async` 的函数内部代码就是异步的,实际都还是同步的,把代码改成这样大家就明白了:
|
||
|
|
||
|
```js
|
||
|
function a() {
|
||
|
return new Promise(function(resolve, reject) {
|
||
|
a += 1
|
||
|
console.log('inner', a)
|
||
|
throw new Error('123')
|
||
|
})
|
||
|
}
|
||
|
```
|
||
|
|
||
|
另外发现还有同学疑问为什么 `throw` 出去的错误被 `promise catch` 住了,这个我们直接看标准:
|
||
|
|
||
|
[标准具体地址](https://tc39.es/ecma262/#sec-control-abstraction-objects)
|
||
|
|
||
|
[这里也有一个不错的作答](https://github.com/KieSun/fucking-frontend/issues/2#issuecomment-793266365)
|