仔細研究了es6的generator function + [co](https://github.com/tj/co "co")
才發現可以利用它來改善我們的程式寫法
讓程式的可讀性更高
先讓我們看看用Promise來撰寫非同步code的樣子
```javascript
let num = function (num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num+1);
}, 500);
});
}
num(1).then((res) => {
return num(res);
}).then((res) => {
return num(res);
}).then((res) => {
// output
// promise result: 4
console.log(`promise result: ${res}`);
});
```
接下來讓我們來看看generator function + [co](https://github.com/tj/co "co")的寫法
```javascript
let num = function (num) {
return (callback) => {
setTimeout(function() {
callback(null, num+1);
}, 500);
}
}
co(function*() {
let num1 = yield num(1);
let num2 = yield num(num1);
let num3 = yield num(num2);
return num3;
}).then((res) => {
// output
// generator result: 4
console.log(`generator result: ${res}`);
});
```
[jsfiddle](https://jsfiddle.net/recca0120/eocp5h2c/ "jsfiddle範例")