應用場景:通俗點說,第二接口的發送數據需要需要第一個接口的返回數據,第三個接口的發送數據需要第二個接口的返回數據;如果你說可以不用Promise,我們可以每個接口的回調裏再去請求下一個接口,也沒問題。缺點:就是看着很不舒服,代碼複用率低。
小程序Promise項目實戰應用:(適合入門前端)
1.單個接口,無依賴關係。舉例,公共方法抽離:如util.js中封的ajax
class CommonUtil {
constructor() {
this.url = "https://www.baidu.com/";
}
getAjax(url, params) {
wx.showNavigationBarLoading();
let that = this;
let getA = function (resolve, reject) {
wx.request({
url: that.url + url,
header: {
'content-type': 'application/json',
'cookie': wx.getStorageSync("peak_view_mini_cookie")
},
dataType: "json",
data: params,
success: function(res) {
wx.hideNavigationBarLoading();
if (res.data.e == "9999") {
resolve(res.data.data); //對應then
} else{
reject(res); //對應catch
that.showMsg(res.data.m);
}
},
fail: function(res) {
reject(res); //對應catch
}
})
}
return new Promise(getA)
}
showMsg(msg) {
wx.showToast({
title: msg,
duration: 2000
})
}
}
module.exports = {
commonUtil: new CommonUtil()
}
舉例index.js頁面的調用
const util = require('../../utils/util.js');
page({
onLoad:function(){
util.commonUtil.getAjax("PeakViewMini/isReadArticle", params).then((data)=>{
//這裏的data是返回的數據,對應公用方法裏的resolve(data)
}).catch((data)=>{
//這裏的data是拋出的錯誤或者非成功狀態碼下自定義拋出的提示,對應catch(data)
})
}
})
2.接口間依次依賴,如3依賴2,2依賴1
page({
onLoad:function(){
let that=this;
util.commonUtil.getAjax("PeakViewMini/getArticle", that.data.params).then((data) => {//1接口
that.data.bannerInfo = that.data.bannerInfo.concat(data);
that.setData({
bannerInfo: that.data.bannerInfo
});
let someData = '傳到下個接口的data';
return new Promise((resolve, reject) => {
//2接口
that.nextOhter(resolve, reject, someData);
})
}).then((data) => {
//3接口
console.log(data); //上一個nextOther函數傳來的data
console.log("2"); //會在上一個nextOther函數執行完成且成功後打印
})
},
nextOhter(resolve, reject, someData) {
setTimeout(function () {
console.log("1");
resolve(someData) //傳到下一接口的data
}, 3000)
}
})
A.then(B).then(C).catch("錯誤處理");A,B,C均爲Promise對象。(個人理解:第二個then是B這個Promise對象對應的then)
看了很多博文才應用到了項目中,瞭解的Promise太淺了,肯定有不足的地方,請大家指正,謝謝!