Generator,async/await语法糖
文章目录
Generator 生成器函数,和普通函数比就是多了个*(星号)。调用生成器函数并不会立即自行,而是会得到一个生成器对象,直到调用next()方法。
function * fn(){
console.log("print")
const res = yield 'foo';
console.log(res);
try{
...
}catch(e){
console.log(e);
}
}
const generator = fn();
generator.next('para');
generator.throw(new Error('handle throw'));函数体内可以添加yield关键字,他相当于暂停函数,直到执行next()方法。next()方法可以传入参数,它将作为yielf方法的返回值。
函数体外执行生成器函数的throw()方法则是手动抛出一个异常。让生成器内部接收。
一个Generator实例
function ajax(url) {
...
}
function* fn() {
const res1 = yield ajax('...');
console.log(res1);
const res2 = yield ajax('...');
console.log(res2);
}
const g = fn();
const result = g.next();
result.value.then(data => {
const result2 = g.next(data);
if (result2.done)
return
result2.value.then(data => {
g.next(data);
})
})这种写法看起来会更加像同步代码,更加扁平化。调用生成器then()方法最好判断结果的done属性是否为true。为true时已经结束,没必要再往下进行。
async/await语法糖async/await语法糖在使用上和generator比更加方便,*号替换成async,yield替换成await。并且async函数会返回一个promise对象,更方便操作

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论