From 87bd8291d5d78e37bd764b32e54c6bcf0b0f0ab0 Mon Sep 17 00:00:00 2001 From: xuwu Date: Wed, 10 Mar 2021 07:42:26 +0800 Subject: [PATCH] feat: update answer --- Answer/1 ~ 10/2.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Answer/1 ~ 10/2.md diff --git a/Answer/1 ~ 10/2.md b/Answer/1 ~ 10/2.md new file mode 100644 index 0000000..1663ff4 --- /dev/null +++ b/Answer/1 ~ 10/2.md @@ -0,0 +1,32 @@ +```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)