


JavaScript asynchronous programming: specific methods of asynchronous data collection_javascript skills
Asyncjs/seriesByHand.js
var fs = require('fs');
process.chdir('recipes'); // Change working directory
var concatenation = '';
fs.readdir('.', function(err, filenames) {
if (err) throw err;
function readFileAt(i) {
var filename = filenames[i];
fs.stat(filename, function(err, stats) {
if (err) throw err;
if (! stats.isFile()) return readFileAt(i 1);
fs.readFile(filename, 'utf8', function(err, text) {
if (err) throw err;
concatenation = text;
if (i 1 === filenames.length ) {
’ to ’ never ’ to ’ never to ’ });
}
readFileAt(0);
});
As you can see, the asynchronous version has a lot more code than the synchronous version. If you use synchronous methods such as filter and forEach, the number of lines of code is only about half, and it is much easier to read. How nice it would be if there were asynchronous versions of these nifty iterators! Use Async.js to do just that!
You may have noticed that in the above code example, the author ignored the advice I gave in Section 1.4: throwing exceptions from callbacks is a bad design, especially in a production environment. However, there is no problem with a simple example that throws an exception directly. If an unexpected error occurs in your code, throw will shut down the code and provide a nice stack trace explaining the cause of the error.
What’s really wrong here is that the same error handling logic (i.e. if(err) throw err) is repeated as many as 3 times! In Section 4.2.2, we'll see how Async.js can help reduce this duplication.
Functional writing method of Async.js
We want to replace the filter and forEach methods used by synchronous iterators with corresponding asynchronous methods. Async.js gives us two options.
async.filter and async.forEach, which process the given array in parallel.
async.filterSeries and async.forEachSeries, they will process the given array sequentially.Running these asynchronous operations in parallel should be faster, so why use a sequential approach? There are two reasons.
There is an upper limit on the number of files that Node and any other application process can read simultaneously. If this upper limit is exceeded, the operating system will report an error. If you can read the file sequentially, you don't need to worry about this limitation.
So now let’s understand async.forEachSeries first. The data collection method of Async.js is used below, and the code implementation of the synchronous version is directly rewritten.
var dirContents = fs.readdirSync('.');
async.filter(dirContents, isFilename, function(filenames) {
async.forEachSeries(filenames, readAndConcat, onComplete);});
function isFilename(filename, callback) {
fs.stat(filename, function(err, stats) {
if (err) throw err;
callback(stats.isFile());
}
function readAndConcat(filename, callback) {
fs.readFile(filename, 'utf8', function(err, fileContents) {
if (err) return callback(err);
concatenation = fileContents ;
});
}
function onComplete(err) {
if (err) throw err;
console.log(concatenation);
}
Now our code is beautifully divided into two parts: task overview (in the form of async.filter call and async.forEachSeries call) and implementation details (in the form of two iterator functions and a completion callback onComplete).
filter and forEach are not the only Async.js utility functions that correspond to standard functional iteration methods. Async.js also provides the following methods:
reject/rejectSeries, just the opposite of filter;
map/mapSeries, 1:1 transformation;
reduce/reduceRight, the gradual transformation of values;
detect/detectSeries, find the value matching the filter;
sortBy, produces an ordered copy;
some, tests whether at least one value meets the given criteria;
every, tests whether all values meet the given criteria.
These methods are the essence of Async.js, allowing you to perform common iterative work with minimal code duplication. Before continuing to explore more advanced methods, let's look at error handling techniques for these methods.
Async.js error handling technology
If you want to blame it, blame Node’s fs.exists for being the first to do this! And this also means that iterators that use Async.js data collection methods (filter/filterSeries, reject/rejectSeries, detect/detectSeries, some, every, etc.) cannot report errors.
For all Async.js iterators that are not boolean, passing a non-null/undefined value as the first parameter of the iterator callback will immediately call the completion callback with the error value. This is why readAndConcat works without throw.
Asyncjs/forEachSeries.js
function readAndConcat(filename, callback) {
fs .readFile(filename, 'utf8', function(err, fileContents) {
if (err) return callback(err);
concatenation = fileContents;
callback();
});
}
So, if callback(err) is indeed called in readAndConcat, this err will be passed to the completion callback (ie onComplete). Async.js is only responsible for ensuring that onComplete is called only once, regardless of whether it is called because of the first error or when all operations are successfully completed.
Asyncjs/forEachSeries.js
function onComplete(err) {
if (err ) throw err;
console.log(concatenation);
}
Node’s error handling convention may not be ideal for Async.js data collection methods, but for Async. As with all other methods in js, adhering to these conventions allows errors to flow cleanly from each task to the completion callback. We'll see more examples of this in the next section.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.