官术网_书友最值得收藏!

  • Node.js Design Patterns
  • Mario Casciaro Luciano Mammino
  • 365字
  • 2021-06-18 18:15:07

3 Callbacks and Events

In synchronous programming, we conceptualize code as a series of consecutive computing steps that solve a specific problem. Every operation is blocking, which means that only when an operation is completed, it is possible to execute the next one. This approach makes the code very easy to read, understand, and debug.

On the other side, in asynchronous programming, some operations, such as reading from a file or performing a network request, are launched and then executed "in the background." When we invoke an asynchronous operation, the instruction that follows is executed immediately, even if the previous asynchronous operation has not finished yet. In this scenario, we need a way to get notified when an asynchronous operation completes, and then continue the execution flow using the results from the operation. The most basic mechanism to get notified about the completion of an asynchronous operation in Node.js is the callback, which is nothing more than a function invoked by the runtime with the result of an asynchronous operation.

The callback is the most basic building block on which all other asynchronous mechanisms are based. In fact, without callbacks, we wouldn't have promises, and therefore not even async/await; we also wouldn't have streams or events. This is why it's important to know how callbacks work.

In this chapter, you will learn more about the Node.js Callback pattern and understand what it means, in practice, to write asynchronous code. We will make our way through conventions, patterns, and pitfalls, and by the end of this chapter, you will have mastered the basics of the Callback pattern.

You will also learn about the Observer pattern, which can be considered a close relative of the Callback pattern. The Observer pattern—embodied by the EventEmitter—uses callbacks to deal with multiple heterogeneous events and is one of the most extensively used components in Node.js programming.

To summarize, this is what you will learn in this chapter:

  • The Callback pattern, how it works, what conventions are used in Node.js, and how to deal with its most common pitfalls
  • The Observer pattern and how to implement it in Node.js using the EventEmitter class
主站蜘蛛池模板: 禹城市| 青龙| 涟水县| 云浮市| 西宁市| 会泽县| 印江| 浮山县| 太谷县| 阜城县| 庆阳市| 蒙阴县| 晋中市| 聂拉木县| 色达县| 北流市| 佛冈县| 双桥区| 许昌县| 鞍山市| 托里县| 寿光市| 隆尧县| 天柱县| 西乌珠穆沁旗| 沂水县| 临潭县| 扎囊县| 浮梁县| 买车| 铅山县| 和平县| 乌苏市| 承德市| 泰兴市| 阿坝县| 台南县| 农安县| 沅陵县| 青龙| 通辽市|