首页 > 技术文章 > 小程序 使用promise 操作 异步api

cbywan 2020-03-30 17:30 原文

npm install --save miniprogram-api-promise

  getPhoneNumber: function (e) {
    console.log(e)
    var ivObj = e.detail.iv
    var telObj = e.detail.encryptedData
    var codeObj = "";
    var that = this;
    //执行login
    wx.login({
      success: res => {
        console.log('获取code成功');
        wx.request({
          url: 'https://xxxxxxxx.com/xcx',
          data: {
            code: res.code,
            iv: ivObj,
            encryptedData: telObj
          },
          // 成功的回调
          success: res => {
            console.log(res);
            // 把信息存储到变量
            this.setData({
              userPhoneNum: res.data,
              isShow: true
            })
          }
        })
      }
    });
  }

  用了之后

  getPhoneNumber1: function (e) {
    // console.log(e)
    var ivObj = e.detail.iv
    var telObj = e.detail.encryptedData
    var codeObj = "";
    var that = this;

    //第一步login请求
    wxp.login()
      //第二步得到code之后 请求后台接口
      .then(res => {
      //返回一个promise
       return wxp.request({
          url: 'https://xxxxxxx.com/xcx',
          data: {
            code: res.code,
            iv: ivObj,
            encryptedData: telObj
          }
        })
      })
      //第三步 得出结果
      .then(res => {
        //获取结果 赋值
        this.setData({
          userPhoneNum: res.data.data,
          isShow: true
        })
      });
  }

  

推荐阅读