es6的promise理解

应用场景:通俗点说,第二接口的发送数据需要需要第一个接口的返回数据,第三个接口的发送数据需要第二个接口的返回数据;如果你说可以不用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太浅了,肯定有不足的地方,请大家指正,谢谢!

猜你喜欢

转载自blog.csdn.net/weixin_42315964/article/details/81558185
今日推荐