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:
var
domready
=
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:
var
steps
=
ASQ
.
iterable
();
steps
.
then
(
function
STEP1
(
x
){
return
x
*
2
;
}
)
.
steps
(
function
STEP2
(
x
){
return
x
+
3
;
}
)
.
steps
(
function
STEP3
(
x
){
return
x
*
4
;
}
);
steps
.
next
(
8
).
value
;
// 16
steps
.
next
(
16
).
value
;
// 19
steps
.
next
(
19
).
value
;
// 76
steps
.
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:
var
steps
=
ASQ
.
iterable
();
steps
.
then
(
function
STEP1
(){
return
2
;
}
)
.
then
(
function
STEP2
(){
return
4
;
}
)
.
then
(
function
STEP3
(){
return
6
;
}
)
.
then
(
function
STEP4
(){
return
8
;
}
)
.
then
(
function
STEP5
(){ ...
Get You Don't Know JS: Async & Performance now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.