Home > Web Front-end > JS Tutorial > body text

A detailed introduction to the usage of async and await in Javascript

黄舟
Release: 2017-05-22 11:44:06
Original
1730 people have browsed it

This article mainly introduces the usage of async/awai in Javascript. It will share how async/await works. If you are interested, you can learn more

async/await is one of the important features of ES7 , which is also recognized as an excellent asynchronous solution in the community. At present, the feature of async/await is already a stage 3 recommendation. You can check the progress of TC39. This article will share how async/await works. Before reading this article, I hope you have ES6 related knowledge such as Promise, generator, and yield. Knowledge.

Before introducing async/await in detail, let’s review the current better asynchronous processing methods in ES6. In the following example, the data request uses the request module in Node.js, and the data interface uses the repo code repository details API provided by the Github v3 api document as an example demonstration.

Promise's handling of asynchronous

Although Node.js's asynchronous IO brings good support for high concurrency, it also makes "callbacks" a disaster, which is very difficult. It is easy to cause callback hell. Traditional methods, such as using named functions, can reduce the number of nesting levels and make the code look clearer. However, it will cause a poor coding and debugging experience. You need to often use ctrl + f to find the definition of a named function, which makes the IDE window jump up and down frequently. After using Promise, the number of nesting levels can be reduced very well. In addition, the implementation of Promise uses a state machine, and the process can be well controlled through resolve and reject in the function. You can execute a series of code logic in a sequential chain. The following is an example of using Promise:

const request = require('request');
// 请求的url和header
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);
  });
 });
};

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))
Copy after login

However, Promise still has flaws. It only reduces nesting, but cannot completely eliminate nesting. For example, when multiple promises are executed serially, after the logic of the first promise is executed, we need to execute the second promise in its then function, which will create a layer of nesting. In addition, the code using Promise still looks asynchronous. It would be great if the code written could become synchronous!

Generator's handling of asynchronousness

When it comes to generators, you should not be unfamiliar with it. For callback processing in Node.js, the TJ/Co we often use is implemented using generator combined with promise. Co is the abbreviation of coroutine, which is borrowed from python, lua, etc. Coroutines in the language. It can write asynchronous code logic in a synchronous manner, which makes the reading and organization of 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后面是一个生成器 generator
const 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);
});
Copy after login

async/await processing of asynchronous

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

Whether it is on the Browser or Node.js side, you need to install the following packages.

$ npm install babel-core --save
$ npm install babel-preset-es2015 --save
$ npm install babel-preset-stage-3 --save
Copy after login

It is recommended to use the require hook method officially provided by babel. After entering through require, the next files will be processed by Babel when required. Because we know that CommonJs is a synchronous module dependency, it is also a feasible method. At this time, you need to write two files, one is the startup js file, and the other is the js file that actually executes the program.

Startup file index.js

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

async.js that actually 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();
  // ... 和上面的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));
Copy after login

Note:

  1. async is used The content wrapped in the statement can be executed synchronously, and await controls the execution sequence. Every time an await is executed, the program will pause and wait for the return value of await, and then execute the subsequent await.

  2. The function called after await needs to return a promise. In addition, this function can be an ordinary function, not a generator.

  3. await can only be used in async functions. If used in ordinary functions, an error will be reported.

  4. The Promise object after the await command may result in rejected, so it is best to put 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 pause, and they are wrapped with a layer of async or co to indicate that the code inside can be processed in a synchronous manner. . However, the function followed by await in async/await does not require additional processing. Co needs to write it as a generator.

【Related Recommendations】

1. Javascript free video tutorial

2. Detailed introduction to multi-valued motion of JavaScript motion framework ( Four)

3. JavaScript motion framework’s sample code sharing for multi-object arbitrary value movement (3)

4. How to solve the problem of anti-shake and suspension in JavaScript motion framework Couplet (2)

5. How does the JavaScript motion framework solve the problem of positive and negative speed rounding (1)

The above is the detailed content of A detailed introduction to the usage of async and await in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!