当前位置:网站首页>Async function ------ ES6
Async function ------ ES6
2022-04-23 20:28:00 【Different 213】
async function
ECMAScript 2017 The specification introduces async function , The main purpose of this function is to simplify the use Promises, Asynchronous call operation , And to a group Promises Do something . just as Promises Similar to structured callbacks ,async / await Similar to a combination generator and Promises.
The sample code is as follows :
function resolveAfter2Seconds() {
return new Promise(resolve =>{
setTimeout(()=>{
resolve('resolved');
},2000);
});
}
/*// promise The way let promise = resolveAfter2Seconds(); promise.then((value)=>{ console.log(value); });*/
// async Function mode
async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds();
console.log(result);//resolved
}
asyncCall();
One 、async The syntax structure of a function
(1) Asynchronous function declaration
Asynchronous function declarations are used to define a return Promise Object's asynchronous function . Asynchronous functions are functions that are executed asynchronously through an event loop , It will pass through an implicit Promise Return the result . But if the code uses asynchronous functions , Its syntax and structure will be more like standard synchronization functions .
async function name([param[,param[,...param]]]){
statements}
- name : Represents the function name .
- param : The name of the parameter to be passed to the function .
- statements : Represents a function body statement .
(2) Asynchronous function expression
Asynchronous function expressions are used to define asynchronous functions in expressions .
let name = async function([param1[,param2[,...parmaN]]]){
statements}
- name : Represents the function name .
- param : The name of the parameter to be passed to the function .
- statements : Represents a function body statement .
An asynchronous function expression is very similar to an asynchronous function statement , The grammar is basically the same . The main difference between them is that asynchronous function expressions can omit the function name to create an anonymous function .
return Promise object
async The function returns a Promise object .async Internal function return The value returned by the statement , It's going to be then Method callback function parameters .
// async The function returns promise object
async function myAsync() {
return 'hello world';
}
let promise = myAsync();
promise.then((value) => {
console.log(value);//hello world
})
Two 、await expression
await The expression is used to wait for a Promise object , It can only be used in asynchronous functions .
[return_value] = await expression
- expression : One Promise Object or any value to wait .
- return_value : return Promise The result of object processing . If it's not Promise object , Returns the value itself .
function createPromise() {
return new Promise((resolve, reject) => {
setTimeout(()=>{
resolve(' The execution is successful ');
});
});
}
async function myAsync() {
console.log(' The current asynchronous function has been called ');
var result = await createPromise();
console.log('Promise The result of the execution of the object :' + result)
}
myAsync();
Error handling
To prevent mistakes , Place it in try_catch In the sentence .
function createPromise() {
return new Promise((resolve, reject) => {
setTimeout(()=>{
reject(' Execution failed ');
});
});
}
async function myAsync() {
console.log(' The current asynchronous function has been called ');
try{
var result = await createPromise();
}catch (e) {
console.log('Promise The result of the execution of the object :' + e)
}
}
myAsync();
Promise Object executes a set of Promise object
let promise1 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve('one');
},100);
});
let promise2 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve('two');
},200);
});
let promise3 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve('three');
},300);
});
async function myAsync() {
let result1 = await promise3;
console.log(result1);
let result2 = await promise2;
console.log(result2);
let result3 = await promise1;
console.log(result3);
}
myAsync();
3、 ... and 、 matters needing attention
-
try … catch sentence
await After the order Promise object , The result of the run might be rejected, So it's better to await The expression is placed in try…catch Block of code .
-
Multiple await Asynchronous operation after expression , If there is no secondary relationship , It's better to let them trigger at the same time .
-
await Restrictions on expressions
await Expressions can only be used in async Function , If it is used in ordinary functions , You're going to report a mistake .
版权声明
本文为[Different 213]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210550451095.html
边栏推荐
- Leetcode 1351. Negative numbers in statistical ordered matrices
- Numpy mathematical function & logical function
- Solve the Chinese garbled code of URL in JS - decoding
- Linux64Bit下安装MySQL5.6-不能修改root密码
- Rt-1052 learning notes - GPIO architecture analysis
- WordPress plug-in: WP CHINA Yes solution to slow domestic access to the official website
- DNS cloud school rising posture! Three advanced uses of authoritative DNS
- LeetCode 709、转换成小写字母
- [talkative cloud native] load balancing - the passenger flow of small restaurants has increased
- Plato farm is one of the four largest online IEOS in metauniverse, and the transaction on the chain is quite high
猜你喜欢
How to protect ECs from hacker attacks?
Mathematical modeling column | Part 5: MATLAB optimization model solving method (Part I): Standard Model
CVPR 2022 | querydet: use cascaded sparse query to accelerate small target detection under high resolution
Es error: request contains unrecognized parameter [ignore_throttled]
Identification of bolt points in aerial photography based on perception
Commande dos pour la pénétration de l'Intranet
Installation and use of NVM
Sqoop imports tinyint type fields to boolean type
A useless confession artifact
DNS cloud school | quickly locate DNS resolution exceptions and keep these four DNS status codes in mind
随机推荐
Identification of bolt points in aerial photography based on perception
論文寫作 19: 會議論文與期刊論文的區別
The ODB model calculates the data and outputs it to excel
go-zero框架数据库方面避坑指南
【PTA】L1-006 连续因子
Why does ES6 need to introduce map when JS already has object type
A useless confession artifact
How many hacking methods do you know?
Parsing methods of JSON data in C - jar and jobobject: error reading jar from jsonreader Current JsonReader item
Imitation Baidu map realizes the three buttons to switch the map mode by automatically shrinking the bottom
【栈和队列专题】—— 滑动窗口
Some basic knowledge of devexpress report development
Common form verification
Linux64Bit下安装MySQL5.6-不能修改root密码
SQL gets the latest record of the data table
Solve the Chinese garbled code of URL in JS - decoding
內網滲透之DOS命令
Scripy tutorial - (2) write a simple crawler
On BIM data redundancy theory
[latex] 5 how to quickly write out the latex formula corresponding to the formula