当前位置:网站首页>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 :

边栏推荐
- Tiktok iqiyi announced cooperation, long and short video handshake and reconciliation?
- Worthington carboxyl transfer carbonic anhydrase application and literature reference
- Data governance notes
- Synchronization primitive: lock
- Open source demo | release of open source example of arcall applet
- C language word translation (to help understand the basic meaning of words) is updated from time to time
- How to empty localstorage before closing a page
- Specificity and five applications of Worthington alcohol dehydrogenase
- Visual studio code installation package download slow & Installation & environment configuration & new one-stop explanation
- PG Optimization -- execution plan
猜你喜欢

Example analysis of recombinant monoclonal antibody prosci CD154 antibody

Amd epyc 9654 Genoa CPU cache test exposure L1 bandwidth up to 30tb/s

Kubernetes creates a user with dashboard read-only permission (with exec permission)

Pychart exits pytest mode (run pytest in mode)

Game partner topic: the cooperation between breederdao and monkeyleague kicked off
![Nacos hand to hand teaching [i] dynamic configuration of Nacos](/img/c4/ae29475c795e879683227de5ba3cfc.png)
Nacos hand to hand teaching [i] dynamic configuration of Nacos

Musk responded whether he would upload his brain to the cloud: already did it!

Web Security Foundation - file upload

Pursue and kill "wallet Assassin" all over the network

1260. Two dimensional grid migration: simple construction simulation problem
随机推荐
Tool use of rookie tutorial -- View subclass (implementation class) class diagram in idea
Alibaba cloud released the white paper "upgrade - standardization of data warehouse upgrade delivery"
Six stones Management: the process is only convenient to shirk responsibility, but not helpful to solve problems
Pads copper laying
G025-db-gs-ins-02 openeuler deployment opengauss (1 active and 1 standby)
7.19 - daily question - 408
Kernel structure and design
2022.7.20 linear table
VC hesitates to invest in Henan
record
POM reports an error
Top priority of dry goods: common indicators and terms in data analysis!
Turn: emotional internal friction is the biggest source of inefficiency in your life
Peripherals: interrupt system of keys and CPU
Wireshark introduction and packet capturing principle and process
Commonjs export import
7.20 - daily question - 408
Free personal virtual machine - AWS free EC2 package
The first meta universe auction of Chen Danqing's printmaking works will open tomorrow!
C language word translation (to help understand the basic meaning of words) is updated from time to time