使用Promise对微信小程序wx.request请求方法进行封装

/**
* 封装request请求
*
* 不要掉入回调的地狱中...
*/
function request(url, data = https://www.it610.com/article/{}, method ="POST", ) {
return new Promise(function(resolve, reject) {
wx.request({
url: url,
data: data,
method: method,
header: {
'Content-Type': 'application/json',
},
success: function (res) {
if (res.statusCode == 200) {
if (res.data.code == 0) {
resolve(res.data);
} else {
wx.hideLoading();
wx.showModal({
title: '提示',
content: res.data.msg,
showCancel: false,
success: function (res) { }
})
reject(res.data);
【使用Promise对微信小程序wx.request请求方法进行封装】}
}else{
wx.hideLoading();
wx.showModal({
title: '提示',
content: '网络请求超时!',
showCancel: false,
success: function (res) { }
})
reject();
}
},
fail: function (err) {
wx.hideLoading();
wx.showModal({
title: '提示',
content: '网络请求超时!',
showCancel: false,
success: function (res) { }
})
console.log("err", err);
reject();
}
})
})
}
/**
* 使用方法
*/
//引入封装的工具文件
const apiUtil = require('../../utils/ApiUtil.js');
var data = https://www.it610.com/article/{
name:"小明",
age:18,
sex:0
}
apiUtil.request("http://www.baidu.com", data).then(res => {
console.log("请求成功")
}).catch(err => {
console.log("请求失败")
})
---------------------
作者:春风十里柔情
来源:CSDN
原文:https://blog.csdn.net/qq_42196458/article/details/94460692
版权声明:本文为博主原创文章,转载请附上博文链接!

    推荐阅读