Async await in JavaScript

Source: Internet
Author: User

Async/await is one of the most important features of ES7, and is also recognized as an outstanding asynchronous solution in the community today. At present, async/await This feature is the stage 3 of the proposal, you can see the progress of TC39, this article will share how async/await work, read this article, I hope you have promise, generator, Yield and other ES6 related knowledge.

Before the detailed introduction of the Async/await, the first review of the current ES6 in the relatively good asynchronous processing methods. In the following example, the data request is presented using the request module in node. js, and the data interface is illustrated using the repo code warehouse details API provided by the GitHub V3 API documentation.

Promise Processing of asynchronous

Although node. JS's asynchronous IO provides good support for high concurrency, it also makes "callbacks" a disaster that can easily cause callbacks to hell. Traditional methods such as the use of named functions, although you can reduce the number of nested layers, so that the code looks more clear. But it will result in a poorer coding and debugging experience, and you will often use CTRL + F to find the definition of a named function, which causes the IDE window to bounce back and forth frequently. With promise, you can reduce the number of nested layers very well. In addition, promise implementation of the state machine, in the function can be very good through the resolve and reject process control, you can follow the sequential chain to execute a series of code logic. Here is an example of using promise:

Const request = require (' request ');//  the requested URL and headerconst options = {   url:  ' Https://api.github.com/repos/cpselvis/zhihu-crawler ',  headers: {      ' user-agent ':  ' request '   }};//  get warehouse information const getrepodata =  ()  => {  return new promise (Resolve, reject)  => {     request (options,  (err, res, body)  => {       if  (Err)  {        reject (err);       }      resolve (body);     });   }) ;}; Getrepodata ()   .then (Result)  => console.log (result);)   .catch ((reason)   => console.error (reason););//  here if there are multiple promise sequential executions, the following://  each then executes the next promise//  Getrepodata ()//    .then ((value2)  => {return promise2})//   .then ((VALUE3)  =>  {RETURN PROMISE3})//   .then ((x)  => console.log (x))

However, promise still has flaws, it only reduces nesting, and does not completely eliminate nesting. For example, for multiple promise serial execution, after the first promise logic executes, we need to execute the second promise in its then function, which creates a layer of nesting. In addition, the code that uses promise seems to still be asynchronous, if the writing code can become synchronous how good!

Generator processing of asynchronous

When it comes to generator, you should not feel unfamiliar with it. In node. js for callback processing, we often use the TJ/CO is the use of generator combined with promise to achieve, CO is the abbreviation for coroutine, for reference in Python, Lua and other languages in the association process. It can write asynchronous code logic in a synchronous way, which makes reading and organizing the code clearer and easier to debug.

Const co = require (' Co '); Const request = require (' request '); const options  = {  url:  ' Https://api.github.com/repos/cpselvis/zhihu-crawler ',   headers:  {     ' user-agent ':  ' request '   }};// yield is followed by a generator   generatorconst getrepodata = function*  ()  {  return new promise ( Resolve, reject)  => {    request (options,  (err, res, body )  => {      if  (ERR)  {         reject (err);       }      resolve (body);     });   }); Co (function*  ()  {  const result = yield getrepodata;  //  ...  If there are multiple asynchronous processes, you can put them here, like   // const r1 = yield getr1;  // const r2 = yield getr2;  // const r3  = yield getr3;  //  each yield corresponds to a pause, and after the yield is executed, it waits for the generator return value after it and then executes the subsequent yield logic.   return result;}). Then (function  (value)  {  console.log (value);}, function  (ERR)  {   Console.error (Err.stack);});
Async/await Processing of asynchronous

Although co is an excellent asynchronous solution within the community, it is not a language standard, but a transitional solution. ES7 language level provides async/await to solve the problem of language level. Async/await is now available directly in IE edge, but chrome and node. js are not supported. Fortunately, Babel has already supported Async's transform, so we used it to introduce Babel. Before we start we need to introduce the following package,preset-stage-3 to the async/await compiled files we need.

The following packages need to be installed either on the browser or the node. js side.

$ npm Install babel-core--save$ npm install babel-preset-es2015--save$ npm install babel-preset-stage-3--save

It is recommended to use the Require hook method provided by the Babel official. Is through the require come in, the next file to require the time will go through Babel processing. Because we know that COMMONJS is a synchronous module dependency, it is also a feasible method. This time, you need to write two files, one is the start of the JS file, and the other is a real program to execute the JS file.

Startup file Index.js

Require (' babel-core/register '); require ('./async.js ');

Async.js of the Real execution program

Const request = require (' request ');const options = {  url:  ' https ://api.github.com/repos/cpselvis/zhihu-crawler ',  headers: {     ' User-Agent ':  ' request '   }};const getRepoData =  ()  => {  return  new promise (Resolve, reject)  => {    request (options,  ( Err, res, body)  => {      if  (err)  {         reject (ERR);      }       resolve (body);     });   }); Async function asyncfun ()  { try {    const value =  await getrepodata ();    // ...  is similar to yield above, if there are multiple asynchronous processes, can be placed here, such as      // const r1 = await&nbsP;GETR1 ();     // CONST R2 = AWAIT GETR2 ();     // CONST R3 = AWAIT GETR3 ();    //  each await is equivalent to a pause, Performing an await waits for the function behind it (not the generator) to return the value before executing the rest of the await logic.     return value;  } catch  (ERR)  {     Console.log (err);   }}asyncfun (). Then (X => console.log (' x: ${x} ')). catch (err = > console.error (err));

Note the point:

    • Async is used to state that the contents of the package can be executed synchronously, and the await is performed sequentially, and each time an await is executed, the program pauses waiting for the await return value before executing the await.

    • The function called after the await needs to return a promise, and the function is a normal function, not a generator.

    • An await can only be used in an async function, and will be used in a normal function to make an error.

    • The Promise object at the back of the await command may run as rejected, so it is best to place the await command in the Try...catch code block.

In fact, the use of Async/await and Co is similar, await and yield are suspended, outside the parcel of a layer of async or co to indicate that the code can be processed in a synchronous manner. But async/await inside the await followed by the function does not require additional processing, CO is required to write it into a generator.


Async await in JavaScript

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.