(ticking) console.log('Tick!'); else console.log('Tock!'); ticking = !ticking; } function *clock() { while (true) { yield; console.log('Tick!'); yield; console.log('Tock!'); } } use a variable to store the state with coroutine
= asyncStep3(step2Result); var step4Result = asyncStep4(step3Result); function *generator() { var step1Result = yield asyncStep1; var step2Result = yield asyncStep2; var step3Result = yield asyncStep3; var step4Result = yield asyncStep4; } Hmm…get closer to our goal! So we can write like this:
= asyncStep3(step2Result); var step4Result = asyncStep4(step3Result); function *coroutine() { var step1Result = yield asyncStep1; var step2Result = yield wrapper(asyncStep2, step1Result); var step3Result = yield wrapper(asyncStep3, step2Result; var step4Result = yield wrapper(asyncStep4, step3Result); } ! wow…even closer to our goal! So we can write like this:
which have only one param, the callback. • make a closure to pass params to the original async function function wraper(asyncFn, param) { return function(callback) { asyncFn(param, callback); } }
= yield wrapper(asyncStep2, step1Result); var step3Result = yield wrapper(asyncStep3, step2Result; var step4Result = yield wrapper(asyncStep4, step3Result); }); Look familiar? Yes, it’s a simple version of co and wrapper function is also a simple version of thunkify. Finally we get this:
programming to disappear, because js is born to be async. • The way we writes async codes differ. • Generator brings us a new way to hide callbacks , just like other libs. • But generator is good at dealing with exceptions.