当前位置:网站首页>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
边栏推荐
- C migration project record: modify namespace and folder name
- 內網滲透之DOS命令
- Leetcode 232, queue with stack
- Automatically fill in body temperature and win10 task plan
- Plato farm is one of the four largest online IEOS in metauniverse, and the transaction on the chain is quite high
- Rédaction de thèses 19: différences entre les thèses de conférence et les thèses périodiques
- SQL Server Connectors By Thread Pool | DTSQLServerTP plugin instructions
- Leetcode 542, 01 matrix
- 16MySQL之DCL 中 COMMIT和ROllBACK
- An error is reported in the initialization metadata of the dolphin scheduler -- it turns out that there is a special symbol in the password. "$“
猜你喜欢
内网渗透之DOS命令
After route link navigation, the sub page does not display the navigation style problem
LeetCode 116. 填充每个节点的下一个右侧节点指针
Leetcode 994, rotten orange
[graph theory brush question-4] force deduction 778 Swimming in a rising pool
Handwritten Google's first generation distributed computing framework MapReduce
Tensorflow 2 basic operation dictionary
A useless confession artifact
DOS command of Intranet penetration
. Ren -- the intimate artifact in the field of vertical Recruitment!
随机推荐
JDBC tool class jdbcconutil gets the connection to the database
Linux64Bit下安装MySQL5.6-不能修改root密码
Rt-1052 learning notes - GPIO architecture analysis
Error reported by Azkaban: Azkaban jobExecutor. utils. process. ProcessFailureException: Process exited with code 127
ArcGIS js api 4. X submergence analysis and water submergence analysis
Investigate why close is required after sqlsession is used in mybatties
堡垒机、跳板机JumpServer的搭建,以及使用,图文详细
打新债中签以后怎么办,网上开户安全吗
[problem solving] 'ASCII' codec can't encode characters in position XX XX: ordinal not in range (128)
Leetcode 20. Valid parentheses
The construction and use of Fortress machine and springboard machine jumpserver are detailed in pictures and texts
Operation of numpy array
SIGIR'22 "Microsoft" CTR estimation: using context information to promote feature representation learning
Notes of Tang Shu's grammar class in postgraduate entrance examination English
Mysql database and table building: the difference between utf8 and utf8mb4
How do BIM swindlers cheat? (turn)
An error is reported when sqoop imports data from Mysql to HDFS: sqlexception in nextkeyvalue
2022 - Data Warehouse - [time dimension table] - year, week and holiday
論文寫作 19: 會議論文與期刊論文的區別
Latest investigation and progress of building intelligence based on sati