Home  >  Article  >  Web Front-end  >  Detailed explanation of how async/await works in Javascript

Detailed explanation of how async/await works in Javascript

青灯夜游
青灯夜游forward
2021-01-13 18:46:161697browse

Detailed explanation of how async/await works in Javascript

Related recommendations: "javascript video tutorial"

async/await is one of the important features of ES7 and is currently recognized as excellent in the community Asynchronous solution. Currently, the feature of async/await is already a recommendation for stage 3. You can take a look at the progress of TC39. This article will share how async/await works. Before reading this article, I hope you have relevant knowledge of Promise, generator, yield and other ES6.

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 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 and can easily 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))

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 by using generator combined with promise. Co is the abbreviation of coroutine, which is borrowed from coroutines in languages ​​​​such as python and lua. 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);
});

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.

The following packages need to be installed on both the Browser and Node.js sides.

$ 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 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.

Start file index.js

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

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));

Note:

  • async is used to declare the package inside The content can be executed synchronously, and await controls the execution sequence. Every time an await is executed, the program will pause and wait for the await return value, and then execute the subsequent await.
  • The function called after await needs to return a promise. In addition, this function can be an ordinary function, not a generator.
  • await can only be used in async functions. If used in ordinary functions, an error will be reported.
  • The Promise object behind the await command may result in rejected, so it is best to place the await command in a 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.

For more programming-related knowledge, please visit: Programming Learning! !

The above is the detailed content of Detailed explanation of how async/await works in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete