- Node.js Design Patterns
- Mario Casciaro Luciano Mammino
- 378字
- 2021-06-18 18:15:08
The async library
If you take a look for a moment at every control flow pattern we have analyzed so far, you will see that they can be used as a base to build reusable and more generic solutions. For example, we could wrap the unlimited parallel execution algorithm into a function that accepts a list of tasks, runs them in parallel, and invokes the given callback when all of them are complete. This way of wrapping control flow algorithms into reusable functions can lead to a more declarative and expressive way of defining asynchronous control flows, and that's exactly what async (nodejsdp.link/async) does.
The async library (not to be confused with the async/await keywords, which we will discuss later in this book) is a very popular solution, in Node.js and JavaScript in general, for dealing with asynchronous code. It offers a set of functions that greatly simplify the execution of tasks in different configurations, and it also provides useful helpers for dealing with collections asynchronously. Even though there are several other libraries with a similar goal, async is the de facto standard in Node.js due to its historic popularity, especially when using callbacks to define asynchronous tasks.
Just to give you an idea of some of the most important capabilities of the async module, here is a sample of the functionalities it exposes:
- Execute asynchronous functions over a collection of elements (in series or in parallel with limited concurrency).
- Execute a chain of asynchronous functions (waterfall) where the output of every function becomes the input of the next one.
- Offers a queue abstraction functionally equivalent to the one we implemented with our TaskQueue utility.
- Provides other interesting asynchronous patterns such as race (executes multiple asynchronous functions in parallel and stops when the first one completes).
Check out the async documentation (nodejsdp.link/async) to find out more about the module and to see some examples.
Once you've understood the fundamentals of the asynchronous patterns described in this chapter, you shouldn't rely on the simplified implementations presented here for your everyday control flow needs. Instead, it's better to adopt a broadly used and battle-tested library like async for your production applications, unless your use case is so advanced that you require a custom algorithm.
- 大學(xué)計(jì)算機(jī)基礎(chǔ)(第二版)
- Java應(yīng)用與實(shí)戰(zhàn)
- 劍指JVM:虛擬機(jī)實(shí)踐與性能調(diào)優(yōu)
- Python金融數(shù)據(jù)分析
- Spring Cloud、Nginx高并發(fā)核心編程
- Java Web基礎(chǔ)與實(shí)例教程
- 教孩子學(xué)編程:C++入門圖解
- Magento 1.8 Development Cookbook
- 人人都是網(wǎng)站分析師:從分析師的視角理解網(wǎng)站和解讀數(shù)據(jù)
- Mastering ServiceNow(Second Edition)
- Windows Phone 7.5:Building Location-aware Applications
- PHP從入門到精通(第4版)(軟件開發(fā)視頻大講堂)
- Python深度學(xué)習(xí)原理、算法與案例
- Quantum Computing and Blockchain in Business
- Android驅(qū)動(dòng)開發(fā)權(quán)威指南