What is the value returned by a promise?


#1

Hey guys I’m new in ember. So I’m developing a simple app to get it (MySQL, Ember, Express, Node), when I create a new record (ember-data) it’s saving on the backend via a RESTful API, so when it’s saved i want to return the ID generated by MySQL, my idea was something like this:

movie.save().then(function(idFromBackend){ // stuff }

Maybe I’m not understanding the purpose of a promise… What it is? When can I use it?

Thanks you, and regards from Chile :slight_smile:


#2

If you are using Ember Data your backend should respond with the complete JSON after a post request.

{ 'movie': { 'id':'1', 'name': 'Mystery Science Theater 3000', 'rating': 'superb' }

Ember Data pushes this Json in the store, so you have the model to use

movie.save().then(function(savedModel){ // do something with the model }

If you dont use Ember Data you need to handle that json yourself. Make on Ember.Object or similar.


#3

Wow. Promises are a big topic and there’s lots of stuff on the web. You might be interested to know that Ember uses RSVP.js, a promise library developed by Yehuda Katz, one of the Ember Core/Founder guys. Check out this prezo about RSVP: http://bantic.github.io/talks-promises/#/

To start to answer your question, promises are a newer JS abstraction for handling operations that do not return immediately, that is, “async” style operations. Promises return an object imbued with special methods (like .then) and behavior (like resolving with a value or rejecting with a reason).

Referring to your code snippet, in your .then you will typically want to provide two functions - the first, for handling a successful return from “movie.save” – like storing the ID I suppose, and the second, for handling an unsuccessful return from “movie.save”.