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
functionasyncFn(name){returnnewPromise((resolve)=>{setTimeout(()=>{resolve('my name is '+name)},1000)})}functionfn1(){console.log(asyncFn('leo'))}fn1()//Promise 对象//function*fn2(){console.log(yieldasyncFn('leo'))//调用next()时,运行到yield暂停,返回yield右侧的值。而函数体内默认返回undefined}letgeneratorFn=fn2()functionexec(generatorFn,value){letresult=generatorFn.next(value)if(!result.done){//如果没有执行完毕if(result.valueinstanceofPromise){//如果返回的是Promise对象result.value.then((result)=>{exec(generatorFn,result)})}else{//如果返回的不是Promise对象//执行到最后时,此时yield返回一个值exec(generatorFn,result.value)}}}exec(generatorFn)//my name is leo
2-Promise和generator
//Promise和generatorfunctionasyncFn(name){returnnewPromise((resolve)=>{setTimeout(()=>{resolve('my name is '+name)},1000)})}functionsum(a,b){returnnewPromise((resolve)=>{setTimeout(()=>{resolve(a+b)},1000)})}functionfn(name){sum(1,5).then((num)=>{if(num>6){asyncFn(name).then((value)=>{console.log(value)})}else{console.log('error')}})}fn('harry')//error
//安装Generator函数的执行器(包装器) co//npm install --save-dev co//letco=require('co')functionasyncF(name){returnnewPromise((resolve,reject)=>{setTimeout(()=>{resolve('my name is '+name)},1000)})}functionsum(a,b){returnnewPromise((resolve,reject)=>{setTimeout(()=>{resolve(a+b)},1000)})}function*fn(name){if((yieldsum(2,5))>6){console.log(yieldasyncF(name))}else{console.log('error')}}letfnx=co.wrap(fn)fnx('leo')//node yield.js//1秒后终端显示//my name is leo
The text was updated successfully, but these errors were encountered:
The text was updated successfully, but these errors were encountered: