Appendix B. Advanced Async Patterns
Appendix A introduced the asynquence library for sequence-oriented async flow control, primarily based on Promises and generators.
Now we’ll explore other advanced asynchronous patterns built on top of that existing understanding and functionality, and see how asynquence makes those sophisticated async techniques easy to mix and match in our programs without needing lots of separate libraries.
Iterable Sequences
We introduced asynquence’s iterable sequences in the previous appendix, but we want to revisit them in more detail.
To refresh, recall:
vardomready=ASQ.iterable();// ..domready.val(function(){// DOM is ready});// ..document.addEventListener("DOMContentLoaded",domready.next);
Now, let’s define a sequence of multiple steps as an iterable sequence:
varsteps=ASQ.iterable();steps.then(functionSTEP1(x){returnx*2;}).steps(functionSTEP2(x){returnx+3;}).steps(functionSTEP3(x){returnx*4;});steps.next(8).value;// 16steps.next(16).value;// 19steps.next(19).value;// 76steps.next().done;// true
As you can see, an iterable sequence is a standard-compliant iterator
(see Chapter 4). So, it can be iterated with an ES6 for..of loop, just
like a generator (or any other iterable) can:
varsteps=ASQ.iterable();steps.then(functionSTEP1(){return2;}).then(functionSTEP2(){return4;}).then(functionSTEP3(){return6;}).then(functionSTEP4(){return8;}).then(functionSTEP5(){ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access