This is the 9th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Here are some study notes and exercises for asynchronous programming, chapter 4 of the Nodejs book

For this series, the last article was about functional programming, the link is juejin.cn/post/699430…

Start with the body, after years of synchronous I/O in favor of the reading mind of programming developers.

Multithreading is usually used to solve performance problems caused by cpu-intensive computing, but it is also difficult to solve problems such as locking and synchronization in actual programming from the context switching overhead of scheduling multithreading in the operating system. There is another way to call the underlying operating system interface through C/C ++ and manually complete asynchronous I/O. This way has good performance, but the threshold is relatively high.

Nodejs is innovative in that it brings asynchronous I/O directly to the language and can be used directly in the business.

Advantages of asynchronous programming

Nodejs is based on an event-driven, non-blocking I/O model. With event loops and asynchronous I/O, single-threaded NodeJS is obviously good at handling I/ O-intensive problems, but for CPU-intensive problems, it’s a matter of looking at the capacity of a single thread.

The Fibonacci calculations show that C is the most powerful and NODEJS, which has a V8 engine that compiles JavaScript code into a faster machine language that can be executed directly by a computer, is slightly less powerful. However, if you write Node Addon (a C/C++ extension module), Node can also be comparable to C.

It is recommended that the CPU consumption should not exceed 10ms. A large number of calculations can be broken down into small ones and scheduled through setImmdiate. So whether it’s CPU intensive or I/O intensive, it’s fine.

The difficulty of asynchronous programming

Exception handling

When writing an asynchronous function, as in the following example, because the callback is in a microtask, it is executed after the current event loop completes.

var asyncFunction = function (callback) { 
    process.nextTick(callback);
};
Copy the code

So just write it as usual, try it on the outside. A catch cannot be caught, but an exception within the current event loop can be caught. The wrong way to write it is:

try {
    asyncFunction(callback); 
} catch (e) { 
    // TODO
}
Copy the code

In asyncFunction asyncFunction, err is the first argument received by nodeJS when handling exceptions.

asyncFunction((err, result) = > {
    // TODO
})
Copy the code

When writing an asynchronous function (such as asyncFunction), note that the callback function passed in by the caller must be executed. Returns an exception correctly for the caller to determine.

Implementation of asyncFunction, such as:

var asyncFunction = function (callback) { 
    try {
        const result = JSON.parse(buf);
    } catch (err) {
        err.body = buf;
        err.status = 400;
        return callback(err);
    }
    callback(null, result)
};
Copy the code

The function is too deeply nested

Asynchronous I/O programming may cause problems with multiple asynchronous calls nested, such as reading files from a directory:

fs.readdir(path.join(__dirname, '.. '), function (err, files) {
    files.forEach(function (filename, index) {
        fs.readFile(filename, 'utf8'.function (err, file) { 
            // TODO
        }); 
    });
});
Copy the code

This nesting of dependencies may be understandable, but avoid it if you don’t have dependencies

Block of code

If sleep(1000) is needed to put the thread to sleep, do not write loops that occupy a single-thread CPU for a long time. Use setTimeout whenever possible.

Multithreaded programming

Compared with web workers in the browser, multi-threaded programming can use the child_process basic API and cluster module to do deeper applications

Asynchronous to synchronous

Nodejs will have fewer synchronous programming apis and can be modified to be asynchronous or implemented through library or compilation

The above is the introduction of the advantages and difficulties of asynchronous programming, welcome to comment and like ~