登录

javascript - promise实例执行先后顺序的疑问?

最近因为要做小程序, 就研究了js, 以前是做服务端的,
小程序登录那块比较复杂, 后来回调嵌套太深, 就不断学习, 后来发现了promise,
但是在做promise的时候遇到一个疑问:

我现在把登录流程封装到一个方法(loginFlow)里, 这个方法里不断的then,then,then,catch. 但是我有另一个功能是获取该用户的内容列表, 那么我应该怎么让这个动作在login后执行呢?

难道是在 loginFlow 加个 callback?
还是说在 loginFlow 外层嵌套一层 promise?
总感觉都不是很美, 难道是哪里理解的不对?
初学js和promise, 望高手指导.

下面是代码, loginFlow是封装好的登录顺序
里面的 this._login 就是封装的 wx.login, 返回了 promise
里面的 this._http 就是封装的 wx.request 返回了 promise

  loginFlow: function() {
    var that = this;

    this._login({}).then(function(res) {
      // 用 code 去获取 session
      let options = {
        url: that.globalData.apiDomain + '/mina/session',
        method: 'GET',
        data: {
          code: res.code
        }
      }
      return that._http(options);

    }).then(function(res) {
      // 把 session 放入 storage, 并且获取用户信息
      wx.setStorageSync('session', res.data.session);
      return this._getUserInfo({});

    }).then(function(resUser) {
      // 把用户信息上传
      let options = {
        url: that.globalData.apiDomain + '/mina/user/info',
        method: 'POST',
        data: resUser
      };
      return that._http(options);

    }).then(function(res) {
      // 上传信息结果成功
      if (res.statusCode == 200) {
          // 把用户信息保存到本地
          
      } else {
        // 程序逻辑返回了失败, 提示?
        return Promise.reject(new Error("程序逻辑错误, 保存用户信息失败"));
      }
      
    }).catch(function(err) {
      // 登录出错
      that._alert("登录出错");
    });
  },
# JavaScript
伊谢尔伦 伊谢尔伦 2249 天前 673 次浏览

全部回复(1) 我要回复

  • 怪我咯

    怪我咯2017-05-19 10:49:45

    then 方法接受两个参数,你可以把最后的错误处理放在一起,然后返回promise实例

    回复
    0
  • 取消 回复 发送