Chaining and other Practical Uses for Promises for JavaScript (ECMAScript6, ES2015)

Repo on Github here.

Promises are cool. The best source for Promise API basics is still the API documentation on MDN. Well here’s some news. Promises are awesome and really easy to work with. That article will teach you all about the built in methods, like “all” and “resolve”, we’re going to go over some useful techniques that are not built into the Promise object.

First, let’s do a simple promise.

What if we want to do something sequentially? Promise.all() waits for all of the promised functions, Promise.race waits for one… but a lot of times, we want to run sequences without losing the benefits of asynchronous code.

Next, let’s make it a bit more complex, with issuing the then in the then. Adding the reseting the counter and using our thenableLoop.

| 0 – Working
| 1 – Working
| 2 – Working
| 3 – Working

This outputs like so:

| 0 – Working
| 1 – Working
* 0 – Working
* 1 – Working
* 2 – Working
* 3 – Working
* 4 – Working
* 5 – Working
Done

You can also pass callbacks as promisables…

That outputs…

| 0 – Still Working
| 1 – Still Working

Keep in mind if we passed in promisable, instead of promisable 2 it would look like this:

| 0 – Still Working
| 1 – Working

Finally, let’s look at binding arguments to the promise…

This outputs:

| 0 – Custom String
| 1 – Custom String

You can have very powerful sequences, with non-blocking IO. This is great for real world applications using ES2015/ES6. You could easily replace our timeouts in these examples with AJAX calls, queries to a datastore, complex DOM interactions, or anything else you might want to ensure is done before executing another set of instructions.

Repo on Github here.

Update: Guatom makes a good point (in the comments below), we’re all more familiar with ES2015 concepts, you can avoid using “bind” by using arrow functions, which keep the context of where the function was called. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions