mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2025-05-24 02:02:21 +00:00
docs(let): add do expression
This commit is contained in:
parent
e5b32087c9
commit
fd666def3c
24
docs/let.md
24
docs/let.md
@ -426,6 +426,30 @@ if (true)
|
||||
function f() {}
|
||||
```
|
||||
|
||||
### do 表达式
|
||||
|
||||
本质上,块级作用域是一个语句,将多个操作封装在一起,没有返回值。
|
||||
|
||||
```javascript
|
||||
{
|
||||
let t = f();
|
||||
t = t * t + 1;
|
||||
}
|
||||
```
|
||||
|
||||
上面代码中,块级作用域将两个语句封装在一起。但是,在块级作用域以外,没有办法得到`t`的值,因为块级作用域不返回值,除非`t`是全局变量。
|
||||
|
||||
现在有一个[提案](http://wiki.ecmascript.org/doku.php?id=strawman:do_expressions),使得块级作用域可以变为表达式,也就是说可以返回值,办法就是在块级作用域之前加上`do`,使它变为`do`表达式。
|
||||
|
||||
```javascript
|
||||
let x = do {
|
||||
let t = f();
|
||||
t * t + 1;
|
||||
};
|
||||
```
|
||||
|
||||
上面代码中,变量`x`会得到整个块级作用域的返回值。
|
||||
|
||||
## const命令
|
||||
|
||||
`const`声明一个只读的常量。一旦声明,常量的值就不能改变。
|
||||
|
@ -770,7 +770,7 @@ run(g);
|
||||
|
||||
## Promise.try()
|
||||
|
||||
实际开发中,经常遇到一种情况:不知道函数`f`是同步函数,还是异步操作,但是想用 Promise 来处理它。因为这样就可以不管`f`是否包含异步操作,都用`then`方法指定下一步流程,用`catch`方法处理`f`抛出的错误。一般就会采用下面的写法。
|
||||
实际开发中,经常遇到一种情况:不知道或者不想区分,函数`f`是同步函数还是异步操作,但是想用 Promise 来处理它。因为这样就可以不管`f`是否包含异步操作,都用`then`方法指定下一步流程,用`catch`方法处理`f`抛出的错误。一般就会采用下面的写法。
|
||||
|
||||
```javascript
|
||||
Promise.resolve().then(f)
|
||||
@ -880,3 +880,5 @@ Promise.try(database.users.get({id: userId}))
|
||||
.catch(...)
|
||||
```
|
||||
|
||||
事实上,`Promise.try`就是模拟`try`代码块,就像`promise.catch`模拟的是`catch`代码块。
|
||||
|
||||
|
@ -138,6 +138,7 @@
|
||||
- Ronald Chen, [How to escape Promise Hell](https://medium.com/@pyrolistical/how-to-get-out-of-promise-hell-8c20e0ab0513#.2an1he6vf): 如何使用`Promise.all`方法的一些很好的例子
|
||||
- Jordan Harband, [proposal-promise-try](https://github.com/ljharb/proposal-promise-try): Promise.try() 方法的提案
|
||||
- Sven Slootweg, [What is Promise.try, and why does it matter?](http://cryto.net/~joepie91/blog/2016/05/11/what-is-promise-try-and-why-does-it-matter/): Promise.try() 方法的优点
|
||||
- Yehuda Katz, [TC39: Promises, Promises](https://thefeedbackloop.xyz/tc39-promises-promises/): Promise.try() 的用处
|
||||
|
||||
## Iterator
|
||||
|
||||
@ -232,3 +233,4 @@
|
||||
- SystemJS, [SystemJS](https://github.com/systemjs/systemjs): 在浏览器中加载AMD、CJS、ES6模块的一个垫片库
|
||||
- Modernizr, [HTML5 Cross Browser Polyfills](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#ecmascript-6-harmony): ES6垫片库清单
|
||||
- Facebook, [regenerator](https://github.com/facebook/regenerator): 将Generator函数转为ES5的转码器
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user