【问题标题】:Weird error with promise and ember承诺和余烬的奇怪错误
【发布时间】:2017-01-20 06:13:40
【问题描述】:

我有以下函数,它返回验证的承诺

authenticate: function(options) {
    return new Promise((resolve, reject) => {
      $.ajax({
        url: this.tokenEndpoint,
        type: 'POST',
        headers: {'Content-Type': 'application/json', 'Accept-Encoding': 'gzip, deflate'},
        data: JSON.stringify({
          username: options.identification,
          password: options.password
        })
      }).then(function(response) {
            console.log(response) // I get here object with good properties 
            resolve({
                lastLoginDate: response.lastLoginDate,
                login: response.login,
                name: response.name,
                role: response.role,
                token: response.id_token
              });
          }, function(xhr, status, error) {
            if(error !== undefined) {
              console.log(error);
            }

            var response = xhr.responseText;
              reject(response);
          });
    });

当我调用它并传递正确的用户名和密码时,它返回“未定义”,但是当我传递错误的属性时,我的“拒绝”工作得很好。有人知道为什么我的“then”没有返回预期的输出吗?

  this.get('session').authenticate('authenticator:custom', {'identification': identification, 'password': password})
    .then((data)=>{
      console.log(data); //Undefined <- here is my problem.
    })
    .catch((reason) => {
      console.log(reason); // It works, when pass bad password!
      this.set('errorMessage', reason.error);
    });

【问题讨论】:

  • authenticate 方法只接受一个参数options 但你发送两个参数this.get('session').authenticate('authenticator:custom', {'identification': identification, 'password': password})

标签: javascript jquery ember.js promise


【解决方案1】:

首先,$.ajax 返回一个 jQuery Promise,如今它与原生 Promise 一样好 99.999% - 因此无需将 $.ajax 包装在 Promise 中

其次,.then 接受两个回调参数,onfullfill 和 onrejected,这两个回调都只接收一个参数 - 你的 onrejected 回调永远不会有状态和错误参数 - 所以代码是有缺陷的

在 onfullfilled 回调中,参数是一个数组,是您在 $.ajax 成功调用中获得的 [result, status, jqXHR]

同理,在onrejected回调中,参数是一个数组,为[jqXHR, status, errorThrown]

鉴于此,可以编写身份验证函数

authenticate: function(options) {
    return $.ajax({
        url: this.tokenEndpoint,
        type: 'POST',
        headers: {'Content-Type': 'application/json', 'Accept-Encoding': 'gzip, deflate'},
        data: JSON.stringify({
          username: options.identification,
          password: options.password
        })
    })
    .then(function(arr) {
            var response = arr[0];
            console.log(response);
            // return instead of resolve
            return({
                lastLoginDate: response.lastLoginDate,
                login: response.login,
                name: response.name,
                role: response.role,
                token: response.id_token
            });
        }, function(arr) {
            var xhr = arr[0], status = arr[1], error = arr[2];

            if(error !== undefined) {
                console.log(error);
            }
            var response = xhr.responseText;
            // return a rejection - could "throw response" instead
            return Promise.reject(response);
        }
    );
}

仅供参考 - ES2015+ 你可以编写

.then(function([response, status, xhr]) {
.....
}, function([xhr, status, error]) {
....

【讨论】:

  • 我刚刚在“成功”中传递了回调,而不是使用 resolve-then,但感谢您的努力。
  • 回调?成功? ..我在问题中没有看到任何提及!
  • 承诺我使用了回调
  • 我一直使用 Promise 的错误处理,但是当响应成功时,我会发送不带参数的空解析。我在“成功”中传递参数,从 ajax 作为回调,它对我来说非常有效。
猜你喜欢
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-23
  • 1970-01-01
相关资源
最近更新 更多