JS asynchronous request History and yield

Source: Internet
Author: User
Tags generator generator

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 (the function (user) {    console.log (user);    Return $.get ('/api/products ');}). Then (the 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 * () {    var data = yield $.get ('/api/data ');    Console.log (data);    var user = yield $.get ('/api/user ');    Console.log (user);    var products = yield $.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.


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 lang = {name: ' JavaScript ', birthyear:1995};var it = Iterator (lang); var pair = It.next (); Console.log (pair); ["Name", "JavaScript"]pair = It.next (); Console.log (pair); ["Birthyear", 1995]pair = It.next (); 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.


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 ';    return true;}


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 a = Iter.next (); Console.log (a); {value: ' Hello ', done:false}var b = iter.next (); Console.log (b); {value: ' World ', done:false}var C = Iter.next (); Console.log (c); {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.


The Yieldable objects currently supported is:-promises-thunks (functions)-Array (parallel execution)-objects (par Allel 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 is a simple comparison: the traditional way, sayhello is an asynchronous function, execution helloworld will first output "world" and then output "hello" .

function SayHello () {    return promise.resolve (' Hello '). Then (function (hello) {        console.log (hello);    }); function HelloWorld () {    sayhello ();    Console.log (' World ');} HelloWorld ();



> "World" > "Hello"


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

function Co (gen) {    var it = gen ();    var ret = It.next ();    Ret.value.then (function (res) {        it.next (res);    }); function SayHello () {    return promise.resolve (' Hello '). Then (function (hello) {        console.log (hello);    }); Co (function *helloworld () {    yield SayHello ();    Console.log (' World ');



> "Hello" > "World"


Eliminate callback Pyramids

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

var co = require (' co '); Co (function * () {    yield SayHello ();    Yield Sayworld ();    Yield Saybye ();});



> "Hello" > "World" > "Bye"


Reprinted from: https://www.cnblogs.com/yelongsan/p/6369474.html

JS asynchronous request History and yield

Related Article

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.