Async: Mainly solves the problem of deep internal nesting
Async function fn () {let result = await XXX; }}Copy the code
The characteristics of the async
- Async can only be placed in async functions
- More semantic than Generator (syntactic sugar)
- Await can be a promise object, a number, a string, a Boolean
- The async function returns a Promise object
async function fn () {
return 'welcome'
}
fn().then(res= > {
console.log(res); // welcome
})
Copy the code
- As soon as the Promise state changes to reject after the await statement, the entire async function is interrupted.
async function fn () {
throw new Error('Error ~~~');
}
fn().then(res= > {
console.log(res);
}, err= > {
console.log(err); / / go to the error
})
Copy the code