You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
varstep1=()=>100varstep2=val=>val+2varstep3=val=>val+3varstep4=val=>val+4function*g3(){try{varval1=yieldstep1()varval2=yieldstep2(val1)varval3=yieldstep3(val2)varval4=yieldstep4(val3)// Do something with val4console.log(val4)}catch(e){// Handle any error from step1 through step4}}// 自动执行vartest4=g3()varres=test4.next()while(!res.done){res=test4.next(res.value)}
对于Generator,个人感觉至少要先掌握两个点:
一是Generator的“惰性”的特点,是一种暂停执行的函数。
二是next方法可以带参数,参数作为上一yield的返回值。
如果完全不理解,建议先看Generator的基本语法,这里只给两个例子,简单的过一遍这两个点。
好的,Generator太懒了,要手动next才能一步步执行,很麻烦,那么我们让他自动执行。
可以看的出,我们的g3的代码非常的清晰:想要获取step1的值,作为参数给step2,以此类推,依赖于val1, val2, val3 得出val4,并对val4进行后续操作。
那么,我们想把g3这种清晰酷炫的写法运用到异步上,【让异步写起来像同步】可以吗?然而必须保证前一步执行完,才能执行后一步的话,上面这个自动执行部分的写法就不适用于异步操作。
先引用个阮老师es6教程给的例子
虽然 Generator 函数将异步操作表示得很简洁,但是流程管理却不方便(即何时执行第一阶段、何时执行第二阶段)。
但是我们却可以把流程这部分的操作总结出规律:当获取到该步的值val1时,则调用next并把val1传递;当获取到下一步的值val2时,则调用next并把val2传递。这是个始终在获取到值后,再进行下一步操作的过程。因此
下一篇
E.Async function
The text was updated successfully, but these errors were encountered: