我正在使用 ember.js,但遇到 simple auth token 问题。包没有返回被拒绝的 promise ,我不知道为什么。
我试图解决的问题是,如果身份验证被拒绝,则显示错误消息,对于此示例,如果由于任何原因失败,我们甚至可以仅显示硬编码消息。我看到的行为是控制台中显示一些错误,但没有显示任何消息。
POST http://localhost:8000/v1/auth/login/400(错误请求)
未定义:_emberMetalLogger["default"].error(error.stack);
// my authenticate action
authenticate: function() {
let store = this.container.lookup('store:main');
let credentials = this.getProperties('identification', 'password'),
authenticator = 'simple-auth-authenticator:token';
let authPromise = this.get('session').authenticate(authenticator, credentials);
authPromise.then(() => {
console.log('inside authPromise');
let userPromise = store.find('user', {username: credentials.identification});
userPromise.then(user => {
console.log("inside userPromise");
store.find('store', {user: user.get('firstObject').get('id')}).then(function(store) {
this.get('appController').set('myStore', store.get('firstObject'));
});
}, err => {
console.log('in error block');
this.set('errorMessage', 'Unable to login with the provided credentials');
});
});
}
我的身份验证操作触发,但它永远无法进入错误 block ,也无法到达 authPromise
内部。一旦定义了 authPromise,错误就会发生,一切都会停止。我什至尝试过在它周围放置一个 try/catch,但我无法得到任何返回值。我希望 promise 会拒绝并使用第二个函数和以下响应。
更深入地了解一下,我想确保这个 promise 被正确地拒绝。在包中,身份验证函数被触发,并且根据我在调试时放入的 console.log()
,它确实拒绝了 promise 。它在拒绝中使用的 2 个变量也已定义,因此我不确定何时没有返回被拒绝的 promise 。
// authenticate action in the ember-simple-auth-token package
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var data = _this.getAuthenticateData(credentials);
_this.makeRequest(data).then(function(response) {
Ember.run(function() {
resolve(_this.getResponseData(response));
});
}, function(xhr) {
Ember.run(function() {
console.log('rejecting');
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},
最佳答案
根据RSVP.js example ,如果 authPromise 拒绝,那么您可能应该在 promise.catch() 而不是 promise.then() 中处理:
authenticate() {
let store = this.container.lookup('store:main');
let credentials = this.getProperties('identification', 'password'),
authenticator = 'simple-auth-authenticator:token';
let authPromise = this.get('session').authenticate(authenticator, credentials);
authPromise.then(() => {
console.log('inside authPromise');
let userPromise = store.find('user', {username: credentials.identification});
userPromise.then(user => {
console.log("inside userPromise");
store.find('store', {user: user.get('firstObject').get('id')}).then(function(store) {
this.get('appController').set('myStore', store.get('firstObject'));
});
}).catch(err => {
console.log('in error block');
this.set('errorMessage', 'Unable to login with the provided credentials');
});
}).catch(reason => {
console.log('Inside authPromise.catch block');
// put your logic here, maybe reason is defined
console.log(reason);
});
}
关于javascript - promise 拒绝不返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32827301/