根据p219的代码改编
示例代码如下
function oneStep(value){ return new Promise(function(resolve, reject){ resolve('one step,' + value); }) } let stepGenerator = function* (){ try{ for(let i =0; i < 10; ++i){ let value = yield oneStep(`step${i}`); console.log(`step${i} complete, value:${value}`); } }catch(e){ console.log('generator e', e); } } function run(generator){ let it = generator(); function go(result){ console.log('go,', result); if(result.done){ console.log('done'); return result.value; } return result.value.then(function(value){ console.log('call go again, then'); return go(it.next(value)); }).catch(function (error){ console.log('call go again, catch'); return go(it.throw(error)) }); } console.log('call go first'); return go(it.next()); } let value = run(stepGenerator); console.log('value', value);
oneStep代表一个执行步骤,是异步执行的。
stepGenerator代表一个流程,内部包含了一系列的步骤
然后在run函数通过递归的方式执行一个流程,上一步执行完了就执行下一步。
输出结果如下
call go first go, { value: Promise { 'one step,step0' }, done: false } value Promise { <pending> } call go again, then step0 complete, value:one step,step0 go, { value: Promise { 'one step,step1' }, done: false } call go again, then step1 complete, value:one step,step1 go, { value: Promise { 'one step,step2' }, done: false } call go again, then step2 complete, value:one step,step2 go, { value: Promise { 'one step,step3' }, done: false } call go again, then step3 complete, value:one step,step3 go, { value: Promise { 'one step,step4' }, done: false } call go again, then step4 complete, value:one step,step4 go, { value: Promise { 'one step,step5' }, done: false } call go again, then step5 complete, value:one step,step5 go, { value: Promise { 'one step,step6' }, done: false } call go again, then step6 complete, value:one step,step6 go, { value: Promise { 'one step,step7' }, done: false } call go again, then step7 complete, value:one step,step7 go, { value: Promise { 'one step,step8' }, done: false } call go again, then step8 complete, value:one step,step8 go, { value: Promise { 'one step,step9' }, done: false } call go again, then step9 complete, value:one step,step9 go, { value: undefined, done: true } done