Table of Contents
Promise's handling of asynchronous
Generator's handling of asynchronousness
async/await processing of asynchronous
Home Web Front-end JS Tutorial Detailed explanation of how async/await works in Javascript

Detailed explanation of how async/await works in Javascript

Jan 13, 2021 pm 06:46 PM
javascript

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

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

Start 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:

  • 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 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 admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles