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
// run (async) a generator to completion// Note: simplified approach: no error handling herefunctionrunGenerator(g){varit=g(),ret;// asynchronously iterate over generator(functioniterate(val){ret=it.next(val);if(!ret.done){// poor man's "is it a promise?" testif(typeofret.value.then==='function'){// wait on the promiseret.value.then(iterate);}// immediate value: just send right back inelse{// avoid synchronous recursionsetTimeout(function(){iterate(ret.value);},0);}}})();}function*foo(){varz=yield3;console.log(z);varw=yield4;console.log(w);}function*bar(){varx=yield1;console.log(x);vary=yield2;console.log(y);yield*foo();varv=yield5;console.log(v);}runGenerator(bar);
4 篇关于 Generator 的文章,从入门到放弃(CSP),里面有几个重要的点:
1. 使用
yield
和return
导致for...of
结果的不同2.
next()
可以传值3. 在 Generator 嵌套 Generator 的顺序是怎样的?
当前迭代器会代理嵌套 Generator 的迭代器,流程如下:
*bar()
的迭代器走到yield *foo()
的点,进入*foo()
完成迭代,再跳出来往下执行。4. 知名 Node.js 库 tj/co 的实现原理
基本上就是自执行 Generator 和 Promise 结合的结果。
The text was updated successfully, but these errors were encountered: