In this chapter, we’ve seen how JavaScript’s single-threadedness is both a blessing and a curse. In the right hands, it makes for beautiful code free of the terrifying race conditions that plague multithreaded apps. But you need to develop the right mind-set—and the right techniques.
The rest of this book is concerned with libraries and design patterns for working with events in JavaScript. All of the examples we’ll look at will run in either mainstream browsers or unmodified Node.js. However, writing JavaScript isn’t the only way to produce JavaScript code. For an overview of some interesting alternatives, see Appendix 1, Tools for Taming JavaScript.
It bears mention here that there is one kind of multithreading in JavaScript: you can spawn worker processes. Each spawned process can exchange data with other processes under the same limitations as any other I/O. Workers make it possible to utilize multiple cores, without breaking the rules of JavaScript (code can’t be interrupted; variables are accessible only within their scope). For more on workers, skip ahead to Chapter 5, Multithreading with Workers.
The next two chapters are devoted to essential design patterns: PubSub, a way of organizing callbacks by assigning them to named events; and Promises, an intuitive object representation for one-shot events.
3.144.17.43