Open oliver1204 opened 5 years ago
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}
var hw = helloWorldGenerator();
hw.next();
hw.next();
hw.next();
hw.next();
// co 库
function co(it){
return new Promise((resolve,reject)=>{
// 异步迭代 next
function next(data){
let {value,done} = it.next(data);
if(!done){
Promise.resolve(value).then(data=>{
next(data)
},reject);
}else{
resolve(value);
}
}
next();
});
}
co(read()).then(data=>{
console.log(data);
});
发展趋势: // generator-runtime搜索 generator简单实现 // async + await 就是 generator + co 库 // 回调 -》 promise -》 generator -》 async + await
简介
async/await 用法
async 函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。当函数执行的时候,一旦遇到 await 就会先返回一个 Promise 对象,等到异步操作完成,再接着执行函数体内后面的语句。
我们先来模拟一个请求:
用then 的方式写,如下:
上面的方法用async/await 的写法,如下:
async/await 错误处理
主动抛出错误
笔者不知道有没有更好的方式,目前笔者借用的是Promise.reject() 方法来处理的。