Being from the Midwest, I make a lot of promises to people, and living in Seattle, I don’t always keep them. We’ll hang out soon! We’ll keep in touch! I’ll totally remember to call you! Yes, when Midwestern hospitality meets the Seattle Freeze, bad things happen.
A note to potential employers: this is a joke. I am a responsible human being and you absolutely want to hire me, I promise.
A promise object is a way to add some synchronicity to asynchronous processes that have dependencies on other processes (see all of those big words? It’s the book-learnin’). If, for example, you tell Ember.js to get the items in the cart and remove an item from the cart, since Ember.js is asynchronous, it will attempt to do both of those things at the same time.
// both of these lines of code will attempt to run at the same time
This means that it will try to save the cart before the cart has been fully created. If you are using the RESTful adapter, this might exhibit as an API call to ‘GET items’ (which should route to ‘items#index’) but without passing any parameters.
You can get around this issue by creating a promise object, like so.
A promise, created in this instance with .then() (they literally use the word “thenable” for objects you can call .then() on. I am not making this up), creates a block of code that is only run after the thenable method is complete. .then() takes up to two arguments. The first argument is the function it will run upon successful creation of the promise object. The second, optional argument is the function it will run upon unsuccessful creation of the promise object.
In this example, we add the promise to the action
cart.get(“items”). This means that the block of code does not run until after that action is complete. In this case, we run
cart.get(“items”), which will make a call to our API and hopefully return an array of items, called
returned_items for clarity. Once that call has been completed, it runs the code inside the block,
returned_items.removeObject(item); foo;. If the API call is unsuccessful (if, for example, it times out), it will run the second function. Frequently, this function will either retry the API call or display an error message.
I know that this is a short and very simple description of a promise object. I ran into the error of parameter-less API calls so often that it seemed like this fundamental understanding of what a promise object is and does was the big takeaway of that project.