Asynchronous Process Control-7 line code learn CO module

Source: Internet
Author: User
Tags generator generator

First please forgive me the title Party (-), TJ great God Co module source code more than 200 lines, obviously not I wait for the cock silk can just a few lines can be rewritten. Just today we all like the "7 days to learn XX language," such as quick-acting elixir, so I also get a similar name "7 Line code learn Co module" to Bo Eyeball.

In order to avoid being dragged out to play small JJ, or first release the so-called 7 lines of code to everyone pressure yajing:

function co(gen) {    var it = gen();    var ret = it.next();    ret.value.then(function(res) {        it.next(res);    });}
The wicked Callbacks

For front-end engineers, asynchronous callbacks are more familiar, the browser's various interactive logic is implemented through event callbacks, the front-end logic is more complex, resulting in more and more callback functions, while the nodejs of the popularity of JavaScript in the back-end of the complex scenes to be applied, in Nodejs Layers of nesting are often seen in code.

The following is a typical asynchronous scenario: first fetching the page data by an asynchronous request, then requesting user information based on the page data, and finally requesting the user's product list based on the user's information. Too many callback functions are nested, making the program difficult to maintain and develop into a vicious callback.

$.get(‘/api/data‘function(data) {    console.log(data);    $.get(‘/api/user‘function(user) {        console.log(user);        $.get(‘/api/products‘function(products) {            console.log(products)        });    });});
Asynchronous Process Control
    • The most primitive asynchronous process of writing, is similar to the above example of the callback function nesting method, the use of people know, it is called a sour cool.

    • Later, Promise, which greatly improved the maintainability of the code, eliminated the evil callback nesting problem, and has now become part of the ES6 standard.

$.get(‘/api/data‘).then(function(data) {    console.log(data);    return $.get(‘/api/user‘);}).then(function(user) {    console.log(user);    return $.get(‘/api/products‘);}).then(function(products) {    console.log(products);});
    • The Co module then appeared on the Nodejs Loop, which was based on ES6 's generator and yield, allowing us to write asynchronous code in a synchronous manner.
co(function *() {    varyield $.get(‘/api/data‘);    console.log(data);    varyield $.get(‘/api/user‘);    console.log(user);    varyield $.get(‘/api/products‘);    console.log(products);});
    • None of the above Promise and generator originally created it for the purpose of solving asynchronous process control. Where Promise is a programming idea for "when XX data is ready, then execute XX action" such a scene, not only asynchronous, synchronous code can also be used Promise. Generator is an iterator generator in ES6, and is controlled by TJ's creative process of asynchronous flow. Real Asynchronous Solutions Please look forward to ES7 async! The following main introduction of the Co module.
CO module

As explained above, the Co module is a Nodejs module that allows us to write asynchronous code in a synchronous form, thanks mainly to the generator of ES6. Nodejs >= Version 0.11 can add --harmony parameters to experience the generator features of ES6, IOJS has been enabled by default for generator.

To understand co, you have to first understand the ES6 of generator and iterator.

Iterator

A Iterator iterator is an object that knows how to remove an item at a time from a collection, and tracks where its current sequence is located, providing a next () method that returns the next item in the sequence.

var‘JavaScript‘1995 };var it = Iterator(lang);var// ["name", "JavaScript"]// ["birthYear", 1995]// A StopIteration exception is thrown

At first glance, it seems that there is nothing peculiar, is not a step by take the object of the key and value, for ... in but also can do, but the combination of it with the generator is very useful.

Generator

The Generator generator allows you to define an iterative algorithm by writing a simple function that can hold its own state.
Generator is a function that can be stopped and then re-entered. The environment of the generator (the bound variable) is saved after each execution and continues to be used the next time it is entered. Generator is literally the "generator" meaning, in ES6 is the iterator generator, which is used to generate an iterator object.

function *gen() {    yield‘hello‘;    yield‘world‘;    returntrue;}

The code above defines a simple generator, which looks like a normal function, except that there is function a number behind the keyword * , and the body of the function can use the yield statement to control the process.

var iter = gen();var// {value:‘hello‘, done:false}var// {value:‘world‘, done:false}var// {value:true, done:true}

When executed gen() , does not execute the generator function body, but returns an iterator. Iterators have next() methods, each time the next () method is called, the function executes to yield the place of the statement. The next () method returns an object that represents the value of the expression after the yield keyword, and the Done property indicates whether the traversal ends. The generator generator next implements the yield process control through the coordination with, the above code executes three times next (), the generator function body only then executes completes.

CO Module ideas

As can be seen from the above example, the generator function body can be stopped at the yield statement until next execution next (). The idea of the Co module is to use this feature of generator to follow the asynchronous operation behind yield, and then trigger the next time after the asynchronous operation completes and returns the result. Of course, the asynchronous operation behind yield needs to follow certain specifications thunks and promises.

Yieldables

The Yieldable objects currently supported are:
-Promises
-Thunks (functions)
-Array (parallel execution)
-Objects (parallel execution)
-Generators (delegation)
-Generator functions (delegation)

7 Lines of code

Then look at the 7 lines of code at the beginning of the article:

function co(gen) {    var it = gen();    var ret = it.next();    ret.value.then(function(res) {        it.next(res);    });}

Start by generating an iterator and then executing the next (), the resulting value is a Promise object, and Promise.then () executes next (). This is, of course, just a primitive demonstration, and many of the logic of error handling and cyclic invocation of next () is not written.

Here's a simple comparison:
The traditional way, sayhello is an asynchronous function, execution helloworld will first output "world" and then output "hello" .

function sayhello() {    returnPromise.resolve(‘hello‘).then(function(hello) {        console.log(hello);    });}function helloworld() {    sayhello();    console.log(‘world‘);}helloworld();

Output

"world""hello"

Co, the output is then output first "hello" "world" .

 function Co(Gen) {    varit = gen ();varret = It.next (); Ret.value.then ( function(res) {It.next (RES); });} function sayhello() {    returnPromise.resolve (' Hello '). Then ( function(hello) {Console.log (hello); });} Co Function *HelloWorld() {    yieldSayHello (); Console.log (' World ');});

Output

"hello""world"
Eliminate callback Pyramids

Suppose sayhello / sayworld / saybye is three asynchronous functions that can be written with a real CO module:

varrequire(‘co‘);co(function *() {    yield sayhello();    yield sayworld();    yield saybye();});

Output

"hello""world""bye"
Reference

"Es7-async" Https://github.com/jaydson/es7-async
The meaning and usage of the Generator function http://www.ruanyifeng.com/blog/2015/04/generator.html
"Iterator" Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator

Asynchronous Process Control-7 lines of code learn Co module

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.