A simple and in-depth study of async and await in JavaScript

A simple and in-depth study of async and await in JavaScript

1. Introduction

The async function, also known as async/await, is a new feature introduced in ES2017 (ES8). Its main purpose is to simplify the syntax required when using Promise-based APIs. async and await keywords allow us to write Promise-based asynchronous behaviors in a more concise way without having to deliberately chain Promise calls.

2. Detailed explanation

​ async means there is asynchronous operation in the function, and await means the expression following it needs to wait for the result. It should be noted that the await keyword is only valid within an async function. If it is used outside the async function body, a syntax error will be thrown.

2.1、async

The async function returns a Promise object, and you can use the then method to add a callback function. As long as async is used, no matter whether the function returns a Promise object or not, it will be wrapped into a Promise object.

Without further ado, let's look at the code to see the effect:

2.1.1. Function returns non-Promise object

async function testAsync() {
    return "hello async";
}

const result = testAsync();
console.log(result); 

It can be seen that when the function returns a string directly, it returns a Promise object, which is equivalent to directly encapsulating the string into a Promise object through Promise.resolve(). If the function does not return a value, the PromiseResult result is undefined.

2.1.2. Function returns Promise object

	async function testAsync() {
		return new Promise(function(resolve, reject) {
			if (true) {
				resolve('resolve return')
			} else {
				reject('reject return')
			}
		})
	}
	console.log(testAsync()); 

It can be seen that the returned object is also a Promise object.

2.2, await

The await keyword can be followed by any variable or expression, but usually await is followed by an asynchronous process. When await is used, it will block the execution of subsequent code. Let’s put async aside for now and talk about await alone.

​ Because await can only be used in functions marked with async, please execute the following examples in the browser console to see the effect.

function testAsync() {
	return new Promise(function(resolve, reject) {
		setTimeout(function() {
			if (true) {
				console.log('Requesting...')
				resolve('resolve return')
			} else {
				reject('reject return')
			}
		}, 2000)
	})
}
var result = await testAsync();
var result1 = await "execute after testAsync";
console.log(result);
console.log(result1); 

It can be seen that after using await, the subsequent code will not be executed until the testAsync method is executed. You can also try removing the async before testAsync to see the difference when adding await.

2.3. Combination of async and await

​ Above we know that await will block the subsequent code execution, so how to solve this problem? You need to use async. After using async, when the function is executed, once await is encountered, a Promise object will be returned first. After the operation after await is completed, the statements in the async function body will be executed.

First, the grammar:

 async function function name() {
 	await XXX;
 }

​ The sample code above:

function testAsync() {
	return new Promise(function(resolve, reject) {
		setTimeout(function() {
			if (true) {
				console.log('Requesting...')
				resolve('resolve return')
			} else {
				reject('reject return')
			}
		}, 2000)
	})
}

function testAsync2() {
	return new Promise(function(resolve, reject) {
		setTimeout(function() {
			if (true) {
				console.log('Requesting 2...')
				resolve('resolve return2')
			} else {
				reject('reject return2')
			}
		}, 2000)
	})
}

async function test() {
	console.log('test started...');
	var value1 = await testAsync();
	console.log(value1);
	var value2 = await testAsync2();
	console.log(value2);
	var value3 = await 'test ends...';
	console.log(value3);
}

console.log(test()); 

​ As can be seen from the figure above, after encountering the first await, the Promise object is immediately returned, and then the testAsync function is executed in sequence, and the testAsync2 function is executed after the testAsync function is executed. It can also be seen that async functions can simplify the syntax of Promise. In the past, we needed to use .then to handle callbacks. Now we can use await to write asynchronous code just like writing synchronous code.

Let's upgrade it and add two more common functions based on the above:

function fun1() {
	return 'Function 1'

}

function fun2() {
	return 'Function 2'
}

function fun3() {
	console.log(fun1());
	console.log(test()); // async/await function console.log(fun2());
}

 console.log(fun3()); 

Let's first sort out the execution process of the function.

1. Execute function 1 first

2. Enter the test function and output start

3. When encountering await in the test function, return the Promise object immediately

4. Execute function 2

5. Execute the testAsync method in the test function

6. After the testAsync method in the test function is executed, continue to execute the testAsync2 method

7. End of test function

It can be seen that the async function will immediately return the Promise object after encountering await, and continue to execute the subsequent logic outside the async function. The async function will be blocked by await and execute the code logic in sequence.

2.4. async and await exception handling

The function after await may have an exception, so it is best to put the await command in a try...catch code block. If the await is a Promise object, you can also use .catch to capture it.

 // The first way to write async function myFunction() {
   try {
     await something();
   } catch (err) {
     console.log(err);
   }
 }
 
 // The second way to write async function myFunction() {
   await somethingPromise()
   .catch(function (err) {
     console.log(err);
   });
 }

3. Summary

​ After encountering await, the async function will immediately return a Promise object and continue to execute the external logic of the async function. The async function will be blocked by await and execute the code logic in sequence.

You can use try...catch or .catch to handle exceptions in async functions.

This concludes this article on an in-depth and easy-to-understand exploration of async and await in JavaScript. For more relevant JavaScript async await content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of JavaScript Promise and Async/Await
  • async/await and promise (asynchronous operation problem in nodejs)
  • Thoroughly understand JavaScript's Promise
  • Detailed explanation of async function in Javascript
  • Detailed explanation of the difference between promise, async and await in Javascript

<<:  Summary of MySQL's commonly used concatenation statements

>>:  Linux sar command usage and code example analysis

Blog    

Recommend

AsyncHooks asynchronous life cycle in Node8

Async Hooks is a new feature of Node8. It provide...

Explanation of factors affecting database performance in MySQL

A story about database performance During the int...

VMware Tools installation and configuration tutorial for Ubuntu 18.04

This article records the installation and configu...

How to install Graphviz and get started tutorial under Windows

Download and installConfigure environment variabl...

What to do if you forget the initial password when installing MySQL on Mac

Forgetting the password is a headache. What shoul...

The textarea tag cannot be resized and cannot be dragged with the mouse

The textarea tag size is immutable Copy code The c...

How to start jar package and run it in the background in Linux

The Linux command to run the jar package is as fo...

Implementation idea of ​​left alignment of the last row of flex box layout

Using flex layout, if it is a nine-square grid, i...

Detailed explanation of MySQL semi-synchronization

Table of contents Preface MySQL master-slave repl...

What are Web Slices?

IE8 new feature Web Slices (Web Slices) Microsoft...

Ubuntu Server 16.04 MySQL 8.0 installation and configuration graphic tutorial

Ubuntu Server 16.04 MySQL 8.0 installation and co...

Nested display implementation of vue router-view

Table of contents 1. Routing Configuration 2. Vue...

Analysis of MySQL's planned tasks and event scheduling examples

This article uses examples to describe MySQL'...

Some common advanced SQL statements in MySQL

MySQL Advanced SQL Statements use kgc; create tab...