Basic usage
Async /await is actually the syntactic sugar of promise. All the effects it can achieve can be realized by promise. It is developed to optimize the then chain of promise.
Async is short for async and await is waiting, so we can understand async declare function is asynchronous and await is waiting for an operation to complete. Syntactically forces await to appear only in async functions.
function timeout(ms) {
return new Promise((resolve) = > {
setTimeout(resolve, ms)
})
}
async function asyncPrint(value, ms) {
await timeout(ms)
console.log(value)
}
asyncPrint('hello'.1000)
Copy the code
The async function returns a Promise object that can be used as an await argument
async function timeout(ms) {
await new Promise((resolve) = > {
setTimeout(resolve, ms)
})
}
async function asyncPrint(value, ms) {
await timeout(ms)
console.log(value)
}
asyncPrint('hello'.1000)
Copy the code
Async functions can be used in many ways
// Function declaration
async function foo () {}
// Function expression
const foo = async function() {}
// Object method
let obj = {
async foo () {}
}
obj.foo().then(...)
// class method
class Storage {
constructor() {
this.cachePromise = cache.open('avatars')}async getAvatar(name) {
const cache = await this.cachePromise
return cache.match(`/avatars/${name}.jpg`)}}const storage = new Storage();
storage.getAvatar('jake'). Then (...).// Arrow function
const foo = async() = > {}Copy the code
The async function returns a Promise object.
The value returned by the return statement inside the async function becomes the parameter returned by the then method.
async function f() {
return 'hello world'
}
f().then(val= > console.log(val))
// 'hello world'
Copy the code
An error is thrown inside the async function, which causes the returned Promise object to be reject Status. The error object is received by the catch method callback
Async function f() {throw new Error(' Error '); } f().then(v => console.log('resolve', v), e => console.log('reject', e)) //reject Error: ErrorCopy the code
Await is followed by a Promise object that returns the deconstruction of the object. If it is not a Promise object, the corresponding value is returned.
async function f() {
// return 123
return await 123
}
f().then(v => console.log(v))
// 123
Copy the code
Javascript has no syntax for sleep, but using await lets the program stay for a specified time
function sleep (interval) {
return new Promise(resolve => {
setTimeout(resolve, interval)
})
}
async function oneSleepAsync() {
for (let i = 0; i < 5; i++) {
console.log(i)
await sleep(1000)
}
}
oneSleepAsync()
Copy the code
If the Promise object following the await command becomes reject, the REJECT argument is received by the catch method callback
async function f() {
await Promise.reject('error')
}
f().then( v=> console.log(v))
.catch(e => console.log(e))
// error
Copy the code