Skip to content

Commit 55831c5

Browse files
committed
edit promise & generator
1 parent c000abd commit 55831c5

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

docs/generator.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,24 @@ Generator函数的本质,其实是提供一种可以暂停执行的函数。yi
6262

6363
yield语句与return语句有点像,都能返回紧跟在语句后面的那个表达式的值。区别在于每次遇到yield,函数暂停执行,下一次再从该位置继续向后执行,而return语句不具备位置记忆的功能。
6464

65+
Generator函数可以不用yield语句,这时就变成了一个单纯的暂缓执行函数。
66+
67+
```javascript
68+
69+
function* f() {
70+
console.log('执行了!')
71+
}
72+
73+
var generator = f();
74+
75+
setTimeout(function () {
76+
generator.next()
77+
}, 2000);
78+
79+
```
80+
81+
上面代码中,只有调用next方法时,函数f才会执行。
82+
6583
## next方法的参数
6684

6785
yield语句本身没有返回值,或者说总是返回undefined。next方法可以带一个参数,该参数就会被当作上一个yield语句的返回值。

docs/promise.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,11 @@ var getJSON = function(url) {
6161

6262
function handler() {
6363
if (this.readyState === this.DONE) {
64-
if (this.status === 200) { resolve(this.response); }
65-
else { reject(this); }
64+
if (this.status === 200) {
65+
resolve(this.response);
66+
} else {
67+
reject(this);
68+
}
6669
}
6770
};
6871
});
@@ -118,6 +121,7 @@ getJSON("/posts.json").then(function(posts) {
118121
// some code
119122
}).catch(function(error) {
120123
// 处理前一个回调函数运行时发生的错误
124+
console.log('发生错误!', error);
121125
});
122126

123127
```

docs/reference.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,13 @@
3131
- Matt Baker, [Replacing callbacks with ES6 Generators](http://flippinawesome.org/2014/02/10/replacing-callbacks-with-es6-generators/)
3232
- Steven Sanderson, [Experiments with Koa and JavaScript Generators](http://blog.stevensanderson.com/2013/12/21/experiments-with-koa-and-javascript-generators/)
3333
- jmar777, [What's the Big Deal with Generators?](http://devsmash.com/blog/whats-the-big-deal-with-generators)
34+
- Marc Harter, [Generators in Node.js: Common Misconceptions and Three Good Use Cases](http://strongloop.com/strongblog/how-to-generators-node-js-yield-use-cases/): 讨论Generator函数的作用
3435

3536
## Promise对象
3637

3738
- Jake Archibald, [JavaScript Promises: There and back again](http://www.html5rocks.com/en/tutorials/es6/promises/)
3839
- Tilde, [rsvp.js](https://github.com/tildeio/rsvp.js)
40+
- Sandeep Panda, [An Overview of JavaScript Promises](http://www.sitepoint.com/overview-javascript-promises/): ES6 Promise入门介绍
3941

4042
## 工具
4143

0 commit comments

Comments
 (0)