小程序pormise异步请求
在utils包下创建request.js
var API = app.data.API_PATH;//请求路径前缀 http://localhost:8080/
const post = (url,data) => {
wx.showLoading({ title: '加载中', })
var promise = new Promise((resolve, reject) => {
console.log("路径为:"+API + url)
console.info("参数为:"+JSON.stringify(data))
wx.request({
url: API + url,
data: data,
method: 'POST',
header: {
'content-type': 'application/json',
},
success: function (res) {
resolve(res);
},
error: function (e) {
reject('网络出错');
},
complete:function(){
wx.hideLoading();
}
})
}).catch((e) => {});;
return promise;
}
// 封装get请求
const get = (url) => {
wx.showLoading({ title: '加载中', })
var promise = new Promise((resolve, reject) => {
console.log("路径为:"+API + url)
wx.request({
url: API + url,
header: {
'content-type': 'application/json',
},
success: function (res) {
resolve(res);
},
error: function (e) {
reject('网络出错');
},
complete:function(){
wx.hideLoading();
}
})
}).catch((e) => {});;
return promise;
}
//多图片上传
const imgurls= (path,url)=> {
var newFile = [];
var promise = new Promise(function(resolve){
path.forEach(element => {
wx.uploadFile({
url: API+ url,
filePath: element,
name: 'file',
success (file){
var data = JSON.parse(file.data)
newFile = newFile.concat(data.data)
if(newFile.length == path.length){ resolve(newFile); }
}
})
});
});
return promise;
}
module.exports = {
get: get,
post: post,
imgurls:imgurls,
}
页面调用
const service = require("../../utils/request.js");
service.get(url).then(function(res){})
service.post(url,data).then(function(res){})