Use of async awai in Javascript, asyncawai

Source: Internet
Author: User

Use of async awai in Javascript, asyncawai

Async/await is one of the important features of ES7 and also an excellent asynchronous solution recognized in the community. Currently, the async/await feature is already recommended for stage 3. Let's take a look at the progress of TC39. This article will share how async/await works. Before reading this article, hope you have knowledge of ES6, such as Promise, generator, and yield.

Before introducing async/await in detail, let's review the best asynchronous processing methods in es6. In the following example, the request module in Node. js is used for data requests. The data interface uses the repo code repository details api provided by the Github v3 API documentation as an example.

Promise asynchronous Processing

Although the asynchronous IO of Node. js provides good support for high concurrency, it also makes "Callback" a disaster, which can easily lead to callback hell. Traditional methods such as using a name function can reduce the number of nested layers and make the Code look clearer. However, this may cause poor coding and debugging experience. You often need to use ctrl + f to find the definition of a designated function, which causes frequent ups and downs of IDE windows. After Promise is used, the nested layers can be effectively reduced. In addition, the implementation of Promise uses a state machine. In the function, you can use resolve and reject to control the process. You can chain the execution of a series of code logic in sequence. The following is an example of Promise:

Const request = require ('request'); // request url and headerconst options = {url: 'https: // api.github.com/repos/cpselvis/zhihu-crawler', headers: {'user-agent ': 'request' }}; // obtain the 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); // if multiple Promise statements are executed sequentially, execute the next promise in each then: // getRepoData ()//. then (value2) =>{ return promise2 })//. then (value3) ==>{ return promise3 })//. then (x) => console. log (x ))

However, Promise still has a defect. It only reduces nesting and cannot completely eliminate nesting. For example, when multiple promise are executed in a serial mode, after the logic of the first promise is executed, we need to execute the second promise in its then function, in this case, a layer of nesting is generated. In addition, the Code using Promise still looks asynchronous. If the code to be written can become synchronous, how nice it is!

Asynchronous processing by Generator

When talking about generator, you should not be unfamiliar with it. In Node. for callback processing in js, we often use TJ/Co to implement it using generator combined with promise. co is the abbreviation of coroutine and is used for reference in coroutine in python, lua and other languages. It can write asynchronous code logic as a synchronous method, which makes the code reading and organization 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 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 flows, put them here, for example, // const r1 = yield getR1; // const r2 = yield getR2; // const r3 = yield getR3; // each yield is equivalent to a pause. After yield is executed, it will wait for the returned value of the generator following it before executing other yield logic. Return result;}). then (function (value) {console. log (value) ;}, function (err) {console. error (err. stack );});

Async/await asynchronous Processing

Although co is an excellent asynchronous solution in the community, it is not a language standard, but a transitional solution. The ES7 language layer provides async/await to solve language-level problems. Currently, async/await can be directly used in IE edge, but chrome and Node. js are not supported yet. Fortunately, babel already supports async transform, so we can introduce babel when using it. Before we start, we need to introduce the following package, which contains the async/await compilation file we need in preset-stage-3.

Install the following package on both Browser and Node. js.

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

We recommend that you use the require hook method officially provided by babel. After the request is passed in, the next file will be processed by Babel during require. Because we know that CommonJs is a synchronous module dependency, it is also feasible. At this time, you need to write two files: one is the started js file and the other is the js file that actually executes the program.

Start file index. js

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

Async. js that truly executes the 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 (); //... similar to yield Multiple asynchronous flows can be stored here, such as // const r1 = await getR1 (); // const r2 = await getR2 (); // const r3 = await getR3 (); // every await is equivalent to pausing. After await is executed, it will wait for the function (not generator) following it to return values before executing other await logic. Return value;} catch (err) {console. log (err) ;}} asyncFun (). then (x => console. log ('x: $ {x }')). catch (err => console. error (err ));

Note:

  1. Async is used to declare that the content in the package can be executed in synchronous mode. await is used to control the execution sequence. Every time an await is executed, the program will pause waiting for the await return value, then run the await command.
  2. The function called after await needs to return a promise. In addition, this function is a common function, rather than a generator.
  3. Await can only be used in the async function. If it is used in a common function, an error is returned.
  4. The Promise object after the await command. The running result may be rejected, so it is best to place the await command in the try... catch code block.

In fact, the usage of async/await is similar to that of co. Both await and yield indicate suspension, and a layer of async or co is wrapped outside to indicate that the code inside can be processed synchronously. However, the functions followed by await in async/await do not require additional processing. co needs to write it as a generator.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.