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 can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

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

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
