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

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function