wepy项目中使用Promise
因为不想陷入异步的回调地域中去,所以在一些复杂的业务当中,我们推荐使用 Promise 或者 async-function 来替代传统的回调,因此需要在项目中单独进行配置。
- 进入项目跟目录,安装依赖
npm install wepy-async-function --save
- 在app.wpy中导入
import 'wepy-async-function';
- 在app.wpy中开启 promise
export default class extends wepy.app {
constructor () {
super();
this.use('promisify');
}
}
4. 判断promiss是否引入成功(在app.wpy的onlaunch中)
onLaunch() {
console.log('on launch');
let mypro = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(123);
}, 2000);
});
mypro.then((r)=>{
console.log(r);
})
}
重启编译后,打印出123即为成功:
Promise简易封装请求一:
utils/request.js
//封装ajax请求
const http = (url,type,parameter) => {
return new Promise((resolve,reject) => {
wx.request({
url:url,
method:type,
success:function (res) {
resolve(res.data);
},
fail:function (err) {
reject(err)
}
})
})
}
export {http}
在index.wpy中使用:
import { http } from '../utils/request';
http("https://easy-mock.com/mock/5cc66aee7a9a541c744c9c07/example/restful/:id/list","GET")
.then(function (res) {
console.log(res)
}).catch(function (err) {
console.log(err)
});
Promise简易封装请求二:
utils/utils.js
//==封装post请求
const post = (url,data) =>{
let promise = new Promise((resolve,reject)=>{
wepy.request({
url: url,
data: data,
header:{'content-type':'applicction/x-www-form-urlencoded'} 或者是 header{'content-type':'application/json'},
success: res=>{
if(res.statusCode ==200){
resolve(res)
}else {
reiect(res)
}
},
fail: err=>{
reject(err)
}
})
})
return promise
}
//==封装get请求
const get =(url,data)=>{
let promise = new Promise((resolve,reject)=>{
wepy.request({
url: url,
data: data,
header: {'content-type': 'application/x-www-form-urlencoded'} 或者是 header: {'content-type': 'application/json'},
success: res=>{
if(res.statusCode ==200){
resolve(res)
}else {
reject(res)
}
},
fail: err=>{
reject(err)
}
})
})
return promise
}
module.exports = {
post: post,
get: get
}
在index.wpy中使用:
const utils = require('../utils/utils.js')
utils.post(url,data).then(res=>{
console.log(res) //====请求成功后
}).catch(err=>{
console.log(err) //====失败后的返回
})