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

Recommend

How to prevent users from copying web page content using pure CSS

Preface When I was typing my own personal blog, I...

Detailed explanation of the use of MySQL select cache mechanism

MySQL Query Cache is on by default. To some exten...

Vue project realizes paging effect

The paging effect is implemented in the vue proje...

Solution to forget password when installing MySQL on Linux/Mac

Preface This article mainly introduces the releva...

How to try to add sticky effect to your CSS

Written in front I don’t know who first discovere...

HTML elements (tags) and their usage

a : Indicates the starting or destination positio...

In-depth interpretation of /etc/fstab file in Linux system

Preface [root@localhost ~]# cat /etc/fstab # # /e...

js to achieve simple drag effect

This article shares the specific code of js to ac...

Analysis of the process of building a cluster environment with Apache and Tomcat

In fact, it is not difficult to build an Apache c...

Detailed explanation of commands to view linux files

How to view linux files Command to view file cont...

Graphical tutorial on installing CentOS 7.3 on VMWare

Illustrated CentOS 7.3 installation steps for you...

Analysis and solution of flex layout collapse caused by Chrome 73

Phenomenon There are several nested flex structur...

How to show or hide common icons on the desktop in Windows Server 2012

Windows Server 2012 and Windows Server 2008 diffe...

JavaScript's unreliable undefined

undefined In JavaScript, if we want to determine ...