Skip to content

Instantly share code, notes, and snippets.

@kalyco
Last active August 29, 2015 14:22
Show Gist options
  • Save kalyco/d4a0a667377896c23092 to your computer and use it in GitHub Desktop.
Save kalyco/d4a0a667377896c23092 to your computer and use it in GitHub Desktop.
//For simple applications,, Ember Data's REST adapter can handle all
//asynchronous calls to the Rails server and completely insulate the
//dev from worrying about what happens when the server takes longer
//to respond than expected.
//If ever required to make a call to the server outside of a Route object's
//Model hook, you'll need to ensure that your application responds properly
//to when the call either fails or succeeds, and not to do anything about the
//call until it returns.
//For this, Ember gives us Promises.
$.ajax("/user/4")
done.function() { // done: perform if call succeeds
alert("success");
})
fail.function() { // fail: perform if call fails
alert("error");
})
always.function() {
alert("complete"); // always: perform for all of the evers
});
// none of these get called until the AJAX call is done.
//Promises are what lie behind the Ember Router when it makes a call in
//the Model hook, pauses for it to resolve, then resumes operation to set up
//the controller
//Promises are what we can use if we need to make calls of our own outside the router.
//example: use promises to ensure that we wait for our Rails server to respond
// with the expanded photo, and to react appropriately whether it succeeded or failed.
//*if using Ember Data we HAVE to rely on promises"
App.ProfilePhotoView = Ember.View.extend({
click.function(evt) {
this.get('controller').send('expandProfilePhoto');
}
});
App.ProfilePhotoController = Ember.ObjectController.extend){
actions: {
expandProfilePhoto: function() {
this.get('store').find('profile_photo', this.get('user_id')).then(
// fulfill
function(answer) {
// display expanded profile photo
},
// reject
function(e) {
// display error message
});
}
}
});
// the find method in Ember Data doesn't return the object it's found.
//What it returns is a Promise. To use that promise properly,
//we can chain a 'then' method on to the end.
//essentially, Promise.then() says,
//"Once you're done, depnding on what happens, these are the callbacks I want run."
//The first callback we provide is the fulfill method -what to do if it succeeds.
//The second is what happens if it rejects, or errors out.
//If you don't lean on Promises, you'll feel tied to only using Ember's model hook in
//the route to get data from the server.
//That can get limiting fast and will lead to some bad dead ends.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment