Async is the syntactic sugar for Generator.
Basic usage
/ / the first
async function fn(){
await 'promise'
}
/ / the second
const fn = async() = > {await 'promise'
}
Copy the code
await
async function fn(){
await 'promise';
// 1. Await a promise or an object containing the then method
// 2. Await the primitive type and call promise. resolve to Promise
}
/ / equivalent to the
async function fn(){
await Promise.resolve('promise')}Copy the code
Promise then syntactic sugar
const p = new Promise(resolve= >{
console.log(3)
resolve('p')})async function fn(){
console.log(1)
const str = await p;
console.log(str)
console.log(2)}/ / equivalent to the
async function fn(){
console.log(1)
p().then(res= >
console.log(res)
console.log(2)})}/ / 1, 3, p. 2
Copy the code
reject
const p = new Promise((resolve,reject) = >{
reject('p')})async function fn(){
await p;
console.log(2) //reject this
}
//1. The error is caught by the FN catch
fn().catch(err= >{
//err p
})
//2. try{}catch
async function fn(){
try{
await p;
}catch(err){
}
console.log(2)}//3. Early capture returns a resolve(new promise)
async function fn(){
await p().catch(err= >resolve(err));
console.log(2)
//p 2
}
Copy the code
The return value Promise
async function fn(){
await 'promise';
return 'value'
}
fn().then(res= >{
// All await are finished, execute
// res value
}).catch(err= >{
//1. Catch the FN error
//2. Await promise
})
Copy the code