This is the 21st day of my participation in the August Text Challenge.More challenges in August !
define
Solutions to asynchronous problems with synchronous thinking
-
Async precedes functions as a keyword
- Any one
async
All functions implicitly return onepromise
- Any one
-
The await keyword can only be used in functions defined using async
- Await can be followed directly by a Promise instance object
- The await function cannot be used alone
-
Async /await makes asynchronous code look and behave more like synchronous code
usage
Await is placed before the Promise call, and await forces the code to wait until the Promise object resolve returns the value of resolve as the result of the await expression
Await can only be used inside async functions, normal functions will get an error if used
async function a(){ console.log('a'); var a = await b(); // When await returns non-promise console.log('12'); } function b(){ console.log('b'); } // return undefined a();Copy the code
The role of async
The async function is responsible for returning a Promise object. If an async function returns an immediate quantity,
Async encapsulates this direct quantity into a Promise object via promise.resolve ();
If async does not return a value, it returns promise.resolve (undefined).
Await role
If an await waits for something other than a promise object, the result of the operation on the following expression is what it waits for
If it is a Promise object, await blocks subsequent code until the Promise object resolve
The way async await functions handle errors
1. Using a try… Catch statement
2. Add a catch callback to the Promise after await
Advantages over Promise
1. Serial synchronous writing method, code reading is relatively easy
2.Async/Await allows try/catch to handle both synchronous and asynchronous errors.
3. Advantage in code clarity when dealing with complex processes
GetAllCategory () {allAppConfig().then((pt) => {this.allapplist = pt.response this.ptname = pt.response[0].name this.ptId = pt.response[0].id getCopyCategory({ appId: this.ptId }).then((lm) => { this.getAllCategoryList = lm.response this.lmName = lm.response[0].categoryName this.categoryId = lm.response[0].categoryId this.getArticleList() }) }) }Copy the code
To:
async getAllCategory() {
let pt = await allAppConfig()
if (pt.code === 200) {
this.allAppList = pt.response
this.ptName = pt.response[0].name
this.ptId = pt.response[0].id
}
let lm = await getCopyCategory({ appId: this.ptId })
if (lm.code === 200) {
this.getAllCategoryList = lm.response
this.lmName = lm.response[0].categoryName
this.categoryId = lm.response[0].categoryId
}
this.getArticleList()
}
Copy the code