About the reuse of code in the Promise instance
The most common Promise instance is probably the AXIos interface. For example, I define the following interface:
function getBooks(params) {
return axios.get('http://localhost:8000/api/books', params)
}
Copy the code
This is a common interface to get background data and is used as follows
Let books getBooks().then(res => {if (res.status == 200) {books = res.data // receive service data} else {console.log(' request failed ')} }). Catch (err => {// catch error console.log(err)})})Copy the code
The points that can be reused are as follows
- Judgment processing of status codes
- Exception handling of interfaces
To unify the processing of Promise instances, we need to package a Promise instance on top of the original Promise instance as follows:
function newGetBooks(params) { return new Promise((resolve, reject) => { axios.get('http://localhost:8000/api/books', Resolve (res.data)} else {console.log(' request failed ') resolve([]) // Return empty array on failed request}}). Catch (err => {// exception handler console.log(' request failed ') resolve([]) // Return empty array on failed exception})})}Copy the code
The usage of encapsulated interfaces is as follows:
let books
newGetBooks().then(res => {
books = res
})
Copy the code