我有以下函数,它返回身份验证的 promise
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);
});
最佳答案
首先,$.ajax 返回一个 jQuery Promise,目前它的性能与原生 Promise 一样好 99.999% - 因此无需将 $.ajax 包装在 Promise 中
其次,.then 采用两个回调参数,onfullfilled 和 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]) {
....
关于javascript - Promise 和 Ember 出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41743174/