“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
My impression of wechat applet is still two years ago when I started. I didn’t know what Promise was, and I only knew that applet requests sometimes nested many layers in the success callback (I later learned that this was called callback hell). Recently, I was given a small program project to develop, and NOW I think I can handle Promise well, so THIS time I also tried to encapsulate wx.Request () to make the request more elegant
First, the official documentation does not support promise-style requests
We’re throughThe official documentationWe can see some specific parameters for the wechat applet to send a request. The following code shows a standard request with wx.request() :
wx.request({
url: "https://xxx.com".method:"POST".data: {phone:187********,
password:'123456'
},
success:res= >{
console.log('Login successful',res)
},
fail:err= >{
console.log('Login failed',err)
}
})
Copy the code
encapsulation
Before wrapping, we need to know a few important parameters for sending a request with wx.request:
- Url – Request address
- Method — Request method (Get/Post, we only encapsulate these two requests here)
- Data — Request parameters
- Success – Callback function successfully invoked by the interface
- Fail – Callback functions that fail to be invoked by the interface
OK, with these parameters in mind we begin formally encapsulating a Promise-style request
/** request.js * encapsulates a promise-style generic request * URL - request address * option - configuration object containing request mode, request parameters */
var app = getApp(); // With global app.js, we can define some common data in globalData, such as baseUrl and token
import Toast from '/@vant/weapp/toast/toast';// Introduce the vant plugin to prompt errors
const request = function(url,options){
reuturn new Promise((resolve,reject) = >{
wx.request({
url:app.globalData.baseUrl+url,
method:options.method,
data:options.method=="GET"? options.data:JSON.stringify(options.data),
// header Is required or not required according to the service situation
header: {'Authorization':'Bearer '+app.globalData.token
},
success: (res) = > {
if (res.data.code == 500) {
Toast(res.data.msg);
reject(res.data.msg)
} else {
resolve(res)
}
},
fail: (err) = > {
reject(err)
}
})
})
}
module.exports = {
// Encapsulate the get method
get(url,data){
reutrn request(url,{
method:"GET",
data
})
}
// Encapsulate the POST method
post(url,data){
return request(url,{
method:"POST",
data
})
}
}
Copy the code
Now that a simple Promise style request is wrapped up, how can we use it
use
// API. Js we manage all interfaces in a unified way
const request = require("./request") // Import the wrapped JS file
module.exports = {
/ / login
login(data){
return request.post('/learn/auth/login',data)
}
}
Copy the code
// login.js
const api = require(".. /.. /api") // Introduce the interface js for consent management
const app = getApp() // Introduce global objects
import Toast from '/@vant/weapp/toast/toast'; // Introduce the vant prompt plug-in
Page({
data: {phone:123456.code:0000
},
/ / login
login() {
if (!this.data.phone.trim()) {
Toast('Please enter the correct mobile phone number');
return
}
let data = {
phone: this.data.phone,
password: this.data.password,
}
api.login(data)
.then(res= > {
console.log('Login successful', res)
wx.reLaunch({
url: '.. /index/index',
})
})
.catch(err= > {
console.log('Login failed', err)
})
},
})
Copy the code
That’s pretty much how it works from package to use, and isn’t it more elegant than the native WX. Requesst