Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
preface
Promise to use and understand async await operations
Async await understand
Async and await are more concise ways to write asynchronous behavior based on promises
async | await |
---|---|
The return value of the function is a Promise object | The expression on the right is typically a Promise object or some other value |
The result of a promise is determined by the async return value | Return success if it’s a Promise object otherwise return the value of the expression |
Async functions can have no await | Await must be written in async function |
* | If the promise of an await fails, an exception is thrown and you need to catch the exception with a try catch |
Async executes synchronously if no await exists | Async execution only with await |
Example of async function successfully used
Create a successful function that returns 1
Executes the function and prints the return value as a Promise object
const fn = async() = > {return 1
}
/* fn is equivalent to const fn = async () => {return promise.resolve (1)} */
const result = fn()
console.log(result)
Copy the code
Example of async function failure
Create a failure function that throws an error of 3 to the browser
Get the promise object with the result variable and get the error with the chain call
const fn = async() = > {throw 3
}
Const fn = async () => {return promise.reject (3)} */
const result = fn()
result.then(
value= > { console.log('onResolved', value) },
reason= > { console.log('onRjected', reason) }
)
Copy the code
The expression to the right of await is a success promise example
The fn function returns a success promise
Use await to avoid getting success values directly with THEN
const fn = () = > {
return Promise.resolve(1)}const fn2 = async() = > {let value = await fn()
console.log(value)
}
fn2()
Copy the code
To the right of aWIAT is an example of a failed promise
The fn function returns a failed promise
If the AWIAT fails to obtain the result, try catch is required
const fn = () = > {
return Promise.reject(1)}const fn2 = async() = > {try {
let value = await fn()
} catch (error) {
console.log(error)
}
}
fn2()
Copy the code
The right-hand side of await is not the Promise example
The result is the returned value
const fn = () = > {
return 6
}
const fn2 = async() = > {let value = await fn()
console.log(value)
}
fn2()
Copy the code
The use of advanced
The following code has a value of 6
Note :fn() returns the success result directly as the promise object await
Async must return a Promise object
const fn = async() = > {return 6
}
const fn2 = async() = > {let value = await fn()
console.log(value)
}
fn2()
Copy the code
conclusion
We can use async functions without await
Today's lesson