Using hash and all with promises in Ember
Starting to learn something new can be difficult all on it's own. There is a lot to learn when it comes to Ember and it can feel daunting. If you have never used promises, then this mountain just got a whole lot higher to climb. There are some tools in Ember that can make working with promises a little easier.
When I first started out using Promises in Ember, a common problem I would run into was needing two promises to resolve before I could take a next step. Often I would solve this problem by doing something like this:
That is anything but elegant. That is where hash comes to the rescue. You can provide
hash with, you guessed it, a hash of promises that will all be resolved before it continues. That means we can rewrite our example like this:
We are able to get rid of the mutable variables and make it clearer what we are trying to do. Even though this is a trivial example, it shows the flexibility
hash can provide.
Another common scenario I would run into is applying some change to an array of objects, all of which need to resolve. Trying to do this without using all is a nightmare. I am not sure what that would even look like. So instead, let us look at an example of what using
all is like:
all makes it easy to create an array of promises that we can resolve and then continue doing work with the results. It is important to note that
all implements a 'fail-fast' method for handling promises that are rejected. This means that as soon as a promise is rejected, processing of the array will halt and the error will be passed down the chain. If you wanted to be able to report an all of the promises that were rejected, you can use allSettled instead.
all are great tools to have around when dealing with promises in Ember. However, they are not the only options available to you. Make sure you take a look at the documentation for Ember.RSVP and checkout some of the awesome tools that you can leverage with promises.
comments powered by Disqus