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. 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 2.1、asyncThe 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 objectasync 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 objectasync 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, awaitThe 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 handlingThe 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:
|
<<: Summary of MySQL's commonly used concatenation statements
>>: Linux sar command usage and code example analysis
Preface When I was typing my own personal blog, I...
MySQL Query Cache is on by default. To some exten...
The paging effect is implemented in the vue proje...
Preface This article mainly introduces the releva...
Written in front I don’t know who first discovere...
a : Indicates the starting or destination positio...
Preface [root@localhost ~]# cat /etc/fstab # # /e...
This article shares the specific code of js to ac...
In fact, it is not difficult to build an Apache c...
background: I have done a project before, which r...
How to view linux files Command to view file cont...
Illustrated CentOS 7.3 installation steps for you...
Phenomenon There are several nested flex structur...
Windows Server 2012 and Windows Server 2008 diffe...
undefined In JavaScript, if we want to determine ...