小程序用Promise简单封装wx.request的POST请求
发布于 5 年前 作者 wliang 4861 次浏览 来自 分享

const inter = ‘主域名’;
var obj={};
const post=(url,obj)=>{
return new Promise( (resolve,reject)=>{
wx.showLoading({ title: ‘加载中’,mask:true})
wx.request({
url: inter+url,
method:‘post’,
data:obj,
header: {
‘content-type’: ‘application/x-www-form-urlencoded’,
},
success: function (res) {
wx.hideLoading();
if (res.statusCode != 200) {
reject({ error: ‘服务器忙,请稍后重试’, code: 500 });
return;
}
resolve(res.data);
},
fail: function (res) {
reject({ error: ‘网络错误’, code: 0 });
},
complete: function (res) {
wx.hideLoading();
}
})
}).catch(err=>{
reject(err)
console.log(‘请求失败了’,err)
})
}

module.exports=post;

4 回复

我是这样子使用的。

const httpGet = (url, param, success, fail) => {

wx.request({

url: url, // 仅为示例,并非真实的接口地址

data: param,

method: ‘GET’,

header: {

‘content-type’: ‘application/json’ // 默认值

},

success,

fail,

complete(res) {

// console.log(‘接口请求完成!’);

},

});

};

const httpPost = (url, param, success, fail) => {

wx.request({

url: url, // 仅为示例,并非真实的接口地址

data: param,

method: ‘POST’,

header: {

‘content-type’: ‘application/x-www-form-urlencoded’ // 默认值

},

success,

fail,

complete(res) {

// console.log(‘接口请求完成!’);

},

});

};

const httpPut = (url, param, success, fail) => {

wx.request({

url: url, // 仅为示例,并非真实的接口地址

data: param,

method: ‘PUT’,

header: {

‘content-type’: ‘application/x-www-form-urlencoded’ // 默认值

},

success,

fail,

complete(res) {

// console.log(‘接口请求完成!’);

},

});

};

const httpDelete = (url, param, success, fail) => {

wx.request({

url: url, // 仅为示例,并非真实的接口地址

data: param,

method: ‘DELETE’,

header: {

‘content-type’: ‘application/json’ // 默认值

},

success,

fail,

complete(res) {

// console.log(‘接口请求完成!’);

},

});

};

token放app.js。可全局引用。我叫雷锋。

const app = getApp();

header: {

’cookie’: app.globalData.token,

},

get到了,我有疑问:wx.request本身就是异步的,为什么要引入Promise呢?

消灭0回复

回到顶部