当前位置:网站首页>How to use ES6 async and await (basic)
How to use ES6 async and await (basic)
2022-07-25 01:38:00 【"Rose has no principle"】
First , These two words can be understood as modifiers . So what is their relationship ? What's the role ? How to use it ?
async and await Keywords allow us to write in a more concise way based on Promise Asynchronous behavior of , Without the need to deliberately chain call promise. It is suggested to read this article before eating promise!
async
async The modifier is to use async Functional Declaration modifier . That is, you add async keyword , You can make this The result of the function To become a promise function :
async function fn1() {}
const a = fn1()
console.log(a);a The result is :

await
await The operator is used to wait for a Promise object . It can only be async Modified asynchronous functions use , however async There can be no await keyword . Generally speaking, it is the same as this word , wait for ! When the function is executed to this place, it will be suspended , Until this gets the return value , Carry on .
When await The right side is
- promise when : The return result is promise Results of processing ;
- Not promise when : Take this value as the return value .
Application example
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ok')
}, 1000);
})
let p2 = new Promise((resolve, reject) => {
reject('fail')
})
async function main() {
//1. Not promise
let res1 = await 10
console.log('res1:', res1);
//2.promise object , success
let res2 = await p1
console.log('res2:', res2);
//3.promise object , Failure ( need try catch Throw an exception )
try {
let res3 = await p2
console.log('res3:', res3);
} catch (e) {
console.log(' Exception thrown :', e);
}
}
main()Output results :

But if in front promise After the function handles the exception , You don't have to try...catch. Because you will get the return value at this time , without return The return value is undefined, If there is a return value, the return value shall prevail .
For example, in p2 Add exception handling at , And specify to return 1( The rest remains the same ):
let p2 = new Promise((resolve, reject) => {
reject('fail')
}).catch(() => {
// The return value is not specified undefined
return '1'
})The result is :

边栏推荐
- Commonjs export import
- Rightmost × Microframe, high quality heif image coding and compression technology
- Data governance notes
- Some of my understanding about anti shake and throttling
- Dynamic kubernetes cluster capacity expansion of airbnb
- Mongodb security cluster construction
- Volley7 – networkdispatcher obtains data from the network [easy to understand]
- Six stones Management: the process is only convenient to shirk responsibility, but not helpful to solve problems
- [summer daily question] Luogu P7550 [coci2020-2021 6] bold
- Wireshark packet capturing and rapid packet location skills
猜你喜欢

EasyX realizes button effect

Synchronization primitive: lock

1260. Two dimensional grid migration: simple construction simulation problem

Vegetable greenhouses turned into smart factories! Baidu AI Cloud helps Shouguang, Shandong build a new benchmark for smart agriculture

Tiktok iqiyi announced cooperation, long and short video handshake and reconciliation?

What does it operation and maintenance management mean? How to establish an effective IT operation and maintenance management system?

Introduction to thread pool

2022.7.20 linear table

Breederdao's first proposal was released: the constitution of the Dao organization

How to implement a state machine?
随机推荐
ES6 modularization
Data governance notes
Luo min cannot become Dong Yuhui
Commonjs export import
Tool use of rookie tutorial -- View subclass (implementation class) class diagram in idea
Ad active directory and domain network
Screenshot of Baidu map
How to implement a state machine?
How to implement the server anti blackmail virus system is a problem we have to consider
Top priority of dry goods: common indicators and terms in data analysis!
Scientific data center resources and user access control system
Wireshark packet capturing and rapid packet location skills
Worthington cytochrome c digestion study carboxypeptidase B scheme
Example analysis of recombinant monoclonal antibody prosci CD154 antibody
Target segmentation for 10000 frames of video, less than 1.4GB of video memory, open source code | ECCV 2022
Ecosystem long-term observation data product system
About the difference between for... In and for... Of and object. Keys()
[summer daily question] Luogu P7550 [coci2020-2021 6] bold
Download files and web pages with WGet
A string "0" was actually the culprit of the collapse of station b