Reputation: 259
Hi I have a doubt in how using promises in Ember. Basically I want to setup the attributes of my controller before running what is next the promise, my code:
export default Ember.Controller.extend({
min: null,
max: null,
isValid: Ember.computed(function(){
var self = this;
var result = new Ember.RSVP.Promise(function(resolve, reject){
var url = "..."
Ember.$.getJSON(url).then(function(data){
if (data[0] === 0){
self.set('errorMessage', "It is a free book");
return false;
} else if (data[0] > 2000){
self.set('errorMessage', "You are poor, go for next");
return false;
} else {
console.log(data); # line 2 of console result
self.set('min', data[1]);
self.set('max', data[2]);
return true;
}
});
});
}
return result;
}),
actions: {
save: function(){
if (this.get('isValid')){
console.log('save action is fired. -- VALID' + '--' + this.get('maxPrice')); # line 1 of console result
} else {
console.log('save action is fired. -- INVALID');
}
}
}
});
The thing is in the third if statement, the code in save action is running before setting the attributes min and max inside the promise. Result in console:
> save action is fired. -- VALID--null
> [9, 1, 20]
Any idea how to set the values before the action go ahead?
Thanks,
Upvotes: 0
Views: 109
Reputation: 47367
There isn't much point in wrapping the jquery promise with another promise. Just use the jquery promise, return it, and then since this is an async world, you need to then
off of that promise.
export default Ember.Controller.extend({
min: null,
max: null,
checkValid: function(url) {
var self = this;
return Ember.$.getJSON(url).then(function(data) {
if (data[0] === 0) {
self.set('errorMessage', "It is a free book");
return false;
} else if (data[0] > 2000) {
self.set('errorMessage', "You are poor, go for next");
return false;
} else {
console.log(data);#
line 2 of console result
self.set('min', data[1]);
self.set('max', data[2]);
return true;
}
});
},
actions: {
save: function() {
var self = this;
var url = ...;
this.checkValid(url).then(function(result) {
if (result) {
console.log('save action is fired. -- VALID' + '--' + self.get('maxPrice'));
} else {
console.log('save action is fired. -- INVALID');
}
});
}
}
});
Additionally when you're using the RSVP promise, you need to actually call resolve
/reject
for the promise to ever resolve or reject. Here's a quick video on how to use RSVP promises: https://www.youtube.com/watch?v=8WXgm4_V85E
Upvotes: 1