Async await in JavaScript

Source: Internet
Author: User
Tags generator

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‘);// 请求的url和headerconst 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);    });  });};getRepoData()  .then((result) => console.log(result);)  .catch((reason) => console.error(reason););// 此处如果是多个Promise顺序执行的话,如下:// 每个then里面去执行下一个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后面是一个生成器 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;  // ... 如果有多个异步流程,可以放在这里,比如  // const r1 = yield getR1;  // const r2 = yield getR2;  // const r3 = yield getR3;  // 每个yield相当于暂停,执行yield之后会等待它后面的generator返回值之后再执行后面其它的yield逻辑。  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();    // ... 和上面的yield类似,如果有多个异步流程,可以放在这里,比如    // const r1 = await getR1();    // const r2 = await getR2();    // const r3 = await getR3();    // 每个await相当于暂停,执行await之后会等待它后面的函数(不是generator)返回值之后再执行后面其它的await逻辑。    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

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.