javascript - Questions about the order in which promise instances are executed?
伊谢尔伦
伊谢尔伦 2017-05-19 10:47:45
0
1
879

Recently, because I wanted to make a small program, I studied js. I used to work on the server side.
The login part of the small program was more complicated. Later, the callbacks were nested too deeply, so I kept learning, and later I discovered promises,
But I encountered a question when making promises:

I now encapsulate the login process into a method (loginFlow), which continuously then, then, then, catch. But I have another function to get the user's content list, then I should How to make this action execute after logging in?

Should I add a callback to loginFlow?
Or should I nest a layer of promises in the outer layer of loginFlow?
It doesn’t always feel very beautiful. Is there something wrong with my understanding?
I am new to js and promises. , looking for expert guidance.

The following is the code, loginFlow is the encapsulated login sequence
This._login inside is the encapsulated wx.login, which returns a promise
This._http inside is the encapsulated wx.request and returns the 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("登录出错");
    });
  },
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
刘奇

The then method accepts two parameters, you can put the final error handling together and return the promise instance

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!