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

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.

Written By StevenLacks

  • Guatom

    Dear Steven:

    Your article was of great help for me, I could get a working implementation based on this for chaining additional paramters. The only downside is that not many people enjoy bind, so I came up with another way to chain additional parameters. In the example before the last one, you could do something like this:

    secondPromise.then(result => [resut, promisable2]).then(callbackable).then(thenable);

    You’d also have to modify the signature of callbackable:

    function callbackable([callback, result]) { …

    Having the code working, thanks to you, it’s easy to see that way of writing the code.

    • This is a good way to do it, I added an update.

  • Rodrigo Enrique Reyes Cornejo

    Guatom, Great remark!!!