Generator and Asynchronous Programming overview

Source: Internet
Author: User
Tags count execution generator readfile

In the 4th chapter of "Node.js", the author gives an in-depth introduction to several asynchronous programming solutions currently prevalent in node and front-end JavaScript, except for the generator solution. But as the node version upgrades and the ECMAScript Harmony features continue to be supported, in version 0.11 we can allow V8 to support generator by enabling--harmory parameters. The development team behind Connect/express has also shifted its energies to new libraries and frameworks, the core library and the framework of Co and KOA, whose main feature is based on generator features in ECMAScript Harmony, This makes it a more elegant implementation of asynchronous programming.

This article describes in depth how the generator is implemented to convert asynchronous programming from raw nested code to flat, sequential code.

Review of asynchronous programming problems

Briefly, there are two problems with asynchronous programming: one is that the return value must be handled through the callback function, and the other is that it is too deep to be nested in a complex case. The following is a simple example of two typical asynchronous scenarios.

Asynchronous serial Read File:

Fs.readfile (' file1.txt ', ' UTF8 ', function (err, txt) {
  if (err) {
    throw err;
  }
  Fs.readfile (txt, ' UTF8 ', function (err, content) {
    if (err) {
      throw err;
    }
    Console.log (content);
  });

To read files asynchronously in parallel:

Fs.readfile (' file1.txt ', ' UTF8 ', function (err, txt) {
  if (err) {
    throw err;
  }
  Console.log (TXT);
});
Fs.readfile (' file2.txt ', ' UTF8 ', function (err, content) {
  if (err) {
    throw err;
  }
  Console.log (content);
});

In both of these scenarios, you can see the string rows because the code is nested, the more calls, the worse the code. For code that reads files asynchronously, it is difficult to know the point at which a parallel asynchronous call is complete, and a variety of asynchronous process libraries are needed to solve the problem.

At present, the main solutions to the problem of asynchronous process control are as follows: three.

Customizing an event Scenario

Promise/deferred

Higher order function Tampering callback function

Since the implementation of these three approaches has been fully covered in the asynchronous programming chapters, the details of the three approaches are no longer detailed. But for the sake of continuity, here is a brief review of the implementation of the third scenario.

The use of higher-order functions in asynchronous programming

Higher-order functions in asynchronous programming, the most widely, most well-known is the async and step of the two libraries, it will be passed in the normal user pass the callback function to wrap up their own special logic functions, and then passed to the asynchronous call. When the asynchronous call ends, the special logic is executed first, and then the callback function that the user passes in. As an example of a simple scenario, it would be useful and straightforward to tamper with a callback function by using a high-order function, assuming that you need to wait for all asynchronous callbacks to execute before you can execute a logic. Here is a simple implementation:

var pending = (function () {
  var count = 0;
  return function (callback) {
    count++;
    return function () {
      count--;
      if (count = = 0) {
        callback ();}};};}
());

var = pending (function () {
  console.log (' all being over ');

Fs.readfile (' file1.txt ', ' UTF8 ', done ());
Fs.readfile (' file2.txt ', ' UTF8 ', done ());

In the above code, done two times, each time the execution of the process, the counter count plus one, and then return a function. When fs.readfile this asynchronous call ends, the execution of the callback function is executed, and the counter is reduced by one. When the counter returns to 0, it means that several callback functions that have been called asynchronously have been executed, and the incoming callback function is executed. Because of the non-blocking reason, the done () generated function is not executed immediately, so that the counter can normally increase the value, and then slowly reduce the value.

Aside from the asynchronous call, for the trial of higher-order functions, the functions to be passed in by the user can be executed. Calls are required in this way:

var = pending (function () {
  console.log (' all being over ');

Done () ();

The function generated here is called immediately, count this counter plus one, immediately minus one, then trigger equals zero condition, so the callback function is executed.

In the solution to the problem of asynchronous programming through generator, there are quite subtle chemical reactions between higher-order functions and generator.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.