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
对象,更不便操作