In projects, most of our requests are wrapped in promises, so why would we want to wrap a request, what good would that do? Let’s look at some code
TestFun: userInfo is an empty array
Since the network request of the applets is an asynchronous request, the data request can continue to execute down the function, so the onLoad request can also continue to execute down the testFun code
Since the request in the applet is an asynchronous one, we can’t do that either
let res = wx.request({
url: xxxx,
method: 'get'
})
Copy the code
So what’s the solution
1. Call testFun in the successful callback
This is fine for simple logic, but with lots of async layers, you have to nest lots of layers and not only is it hard to write, but it’s also very hard to write, and the code is not readable or maintainable. At this point, we need to use promises to solve this problem. With Promises, we can use its chain calls. If you’re not familiar with this article, see: Promise objects
test().then(test1()).then(test2()).then(.....)
Copy the code
2. Use Promise
We can use the Promise to the request of the small program for simple packaging, put the parameters in a small program request object inside, so I enclosed the parameters are encapsulated said coming from the outside, because the project request used very much, encapsulated into a global a js file directly, and then introduce the would be better
At this time, we can also call the wechat wx.getNetWorkType API to obtain the network status, and resolve if there is a network
class Util {
static httpRequest(options) {
let tAccessToken = wx.getStorageSync("access_token");
let tHeader = Object.assign({
"Authorization": 'Bearer ' + tAccessToken
}, options.header)
return new Promise((resolve, reject) => {
wx.request({
url: options.url,
header: tHeader,
method: options.method || "GET",
data: options.data || {},
success(res) {
resolve(res)
},
fail(err) {
reject(err)
},
complete(finish) {
resolve(finish)
}
})
})
}
}
module.exports = Util
Copy the code
Import the JS file where the request is needed, and then call the method directly
const Util = require('.. /.. /utils/util.js') Util.httpRequest({ url: `https://xxx.com/xxx`, data: { a: xxx, b: xxx }, method: 'post', // Header can not be added, the default is added during encapsulation, according to personal actual situation header: {"Authorization": 'Bearer ' + access_token } }).then((res) => { console.log(res) }).catch((err) => { console.log(errr) })Copy the code
Sometimes too many chain calls can be uncomfortable to watch. And there is a possibility of chain hell, so I recommend async, await in ES8
async
Async functions declare async functions that return a promise object. If async functions do not return a promise, they are wrapped in promise.resolve ()
await
1, await the result of the expression on the right, which is a Promise object or some other value.
2. If it waits for something other than a promise, the result of the await expression operation is what it waits for.
3. If it waits for a promise, await is busy. It blocks the following code, waiting for the promise to resolve and then getting the value of resolve as the result of the await expression
async fun(){ let { data: { data, flag, code, message } } = await Util.httpRequest({ url: `https:xxx.com/xxxx`, method: 'get', data: {a: XXX}}) if(code === fixed value){this.setData({CCC: XXXX})} else {wx.showtoast ({title: Failed to get the data message | | ' '})}},Copy the code
Note:
1. Never use a try or catch to catch an error, as this will be digested inside a promise, and you cannot use a try or catch without async or await
2. To catch an asynchronous function error, encapsulate it as promise. reject and then use async and await to catch it. If an asynchronous function has a catch, there is no need to use a try or catch
Avoid the following
async fun(){
try {
let { data: { data, code, message } } = await Util.httpRequest({
url: `${hostCharge}/restaurant/currentOrderWx`,
method: 'get',
header: {
"Authorization": 'Bearer ' + token
},
data: {
userId: userId,
companyId: companyId
}
})
if(code === 20000){
} else {
wx.showToast({
title: message,
})
}
} catch (error) {
console.log(error)
}
},
Copy the code