当前位置:网站首页>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
边栏推荐
- Zdns was invited to attend the annual conference of Tencent cloud basic resources and share the 2020 domain name industry development report
- Some basic knowledge of devexpress report development
- [PTA] get rid of singles
- DNS cloud school rising posture! Three advanced uses of authoritative DNS
- 三十一. `prototype`显示原型属性和`__proto__`隐式原型属性
- ArcGIS js api 4. X submergence analysis and water submergence analysis
- The ODB model calculates the data and outputs it to excel
- Notes of Tang Shu's grammar class in postgraduate entrance examination English
- 打新债中签以后怎么办,网上开户安全吗
- Thirty What are VM and VC?
猜你喜欢
Don't bother tensorflow learning notes (10-12) -- Constructing a simple neural network and its visualization
Zdns was invited to attend the annual conference of Tencent cloud basic resources and share the 2020 domain name industry development report
上海回應“面粉官網是非法網站”:疏於運維被“黑”,警方已立案
Tensorflow 2 basic operation dictionary
Wave field Dao new species end up, how does usdd break the situation and stabilize the currency market?
PIP installation package reports an error. Could not find a version that satisfies the requirement pymysql (from versions: none)
SQL Server Connectors By Thread Pool | DTSQLServerTP plugin instructions
On BIM data redundancy theory
DOS command of Intranet penetration
【栈和队列专题】—— 滑动窗口
随机推荐
上海回應“面粉官網是非法網站”:疏於運維被“黑”,警方已立案
Servlet learning notes
Three. Based on ply format point cloud voxel model JS upload interface writing
[latex] 5 how to quickly write out the latex formula corresponding to the formula
Confusion about thread blocking after calling the read () method of wrapper flow
An error is reported in the initialization metadata of the dolphin scheduler -- it turns out that there is a special symbol in the password. "$“
On BIM data redundancy theory
堡垒机、跳板机JumpServer的搭建,以及使用,图文详细
I JS deep copy and shallow copy
JS arrow function user and processing method of converting arrow function into ordinary function
Solve the Chinese garbled code of URL in JS - decoding
Scripy tutorial - (2) write a simple crawler
黑客的入侵方式你知道几种?
6-5 字符串 - 2. 字符串复制(赋值) (10 分)C语言标准函数库中包括 strcpy 函数,用于字符串复制(赋值)。作为练习,我们自己编写一个功能与之相同的函数。
Shanghai responded that "flour official website is an illegal website": neglect of operation and maintenance has been "hacked", and the police have filed a case
How to protect ECs from hacker attacks?
ArcGIS JS version military landmark drawing (dovetail arrow, pincer arrow, assembly area) fan and other custom graphics
LeetCode 542、01 矩阵
Intersection calculation of straight line and plane in PCL point cloud processing (53)
Notes of Tang Shu's grammar class in postgraduate entrance examination English