1. Application scenarios
When initializing the mini program page, you need to go to the server to obtain the token. The parameters are included in the other two interface requests. The code you write may look like this:
onLoad(options) {
this.getToken()
},
getToken() {
wx.request({
url: '后端API地址1',
success: (res) => {
// console.log(res)
wx.request({
url: '后端API地址2',
success: (data) => {
// console.log(data)
wx.request({
url: '后端API地址3',
success: (r) => {
console.log(r)
}
})
}
})
}
})
},
Callback functions are nested inside callback functions. This is the legendary callback hell. The readability is very poor, and you may cry to maintain it. what to do? Promised.
2. API Promise
1. Method 1
request.js related code
const baseUrl = 'https://www.escook.cn/api'
const sendRequest = (params) => {
// console.log(params)
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + params.url,
method: params.method || 'GET',
data: params.data,
success: res => {
// console.log(res)
resolve(res)
},
fail: err => {
reject(err)
}
})
})
}
export default sendRequest
home.js related code
import sendRequest from "../../utils/request"
Page({
getData() {
sendRequest({
method: 'POST',
url: '/post',
data: {
name: 'buddha', age: 18}
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
},
onLoad(options) {
this.getData()
},
/**省略其它代码*/
})
Home.js related code can also be optimized as follows
import sendRequest from "../../utils/request"
Page({
async getData() {
const res = await sendRequest({
method: 'POST',
url: '/post',
data: {
name: 'buddha', age: 18}
})
console.log(res)
},
onLoad(options) {
this.getData()
},
})
2. Method 2
Right-click to open in an external terminal window
Execute in the terminal npm init -y
and npm i --save miniprogram-api-promise
Click WeChat Developer Tools Build npm option under the tools menu in
After the build is completed, a pop-up box to complete the build will pop up, click OK
There will be more miniprograms in the miniprogram_npm directory A miniprogram-api-promise directory comes out, indicating that the build was successful
The relevant code for app.js is
import {
promisifyAll } from 'miniprogram-api-promise'
const wxp = wx.p = {
}
promisifyAll(wx, wx.p)
The relevant code of home.js is
async getData() {
const res = await wx.p.request({
'url': 'https://www.escook.cn/api/get',
'method' : 'GET',
'data': {
name: 'buddha', age: 18}
})
console.log(res)
},