promise的基本用法:
Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject。
resolve 函数的作用是,将Promise 对象的状态从“未完成”变为“成功”,在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;
reject 函数的作用是,将Promise 对象的状态从“未完成”变为“失败”,在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。
then方法可以接受两个回调函数作为参数。第一个回调函数是Promise 对象的状态变为resolved时调用,第二个回调函数是Promise 对象的状态变为rejected时调用。
下面是一个用Promise对象实现的 Ajax 操作的例子。
function http(path,data,method){
let baseUrl='https://...'
return new Promise((resolve,reject)=>{
wx.request({
url: baseUrl+path,
method,
data,
header:{
'Authorization':wx.getStorageSync('token')
},
success:(res)=>{
resolve(res.data)
},
fail:(err)=>{
reject(err)
}
})
})
}
module.exports={
http:http
}
此时封装好ajax后,可以在创建一个组件,负责进行具体的函数操作。
const {http}=require('./http')
const loginHttp=(path,data,method)=> http(path,data,method)
module.exports={
loginHttp,
}
最后在页面上导入传参
const {loginHttp} = require('../../http/api')
loginHttp('/api/auth/login', {
email: this.data.email,
password: this.data.pwd
},
'POST')
.then(res => {
console.log(res);
let {access_token}=res;
wx.setStorageSync('token', access_token);
})