Back to Home

Promises chaining

Let’s return to the problem mentioned in the chapter info:callbacks: we have a sequence of asynchronous tasks to be performed one after another — for instance, loading scripts. How can we code it well? Promises provide a couple of recipes to do that. In this chapter we cover promise chaining. It looks like this: The idea is that the result is passed through the chain of .then handlers. Here the flow is: 1. The initial promise resolves in 1 second (), 2. Then the .then handler is called (), which in turn creates a new promise (resolved with 2 value). 3. The next then () gets the result of the previous one, processes it (doubles) and passes it to the next handler. 4. …and so on. As the result is passed along the chain of handlers, we can see a sequence of alert calls: 1 -> 2 -> 4. The whole thing works, because every call to a .then returns a new promise, so that we can call the next .then on it. When a handler returns a value, it becomes the result of that promise, so the next .then is called with it. A classic newbie error: technically we can also add many .then to a single promise. This is not chaining. For example: What we did here is just adding several handlers to one promise. They don’t pass the result to each other; instead they process it independently. Here’s the picture (compare it with the chaining above): All .then on the same promise get the same result – the result of that promise. So in the code above all alert show the same: 1. In practice we rarely need multiple handlers for one promise. Chaining is used much more often.

Returning promises

A handler, used in .then(handler) may create and return a promise. In that case further handlers wait until it settles, and then get its result. For instance: Here the first .then shows 1 and returns new Promise(…) in the line (). After one second it resolves, and the result (the argument of resolve, here it’s result 2) is passed on to the handler of the second .then. That handler is in the line (**), it shows 2 and does the same thing. So the output is the same as in the previous example: 1 -> 2 -> 4, but now with 1 second delay between alert calls. Returning promises allows us to build chains of asynchronous actions.

Example: loadScript

Let’s use this feature with the promisified loadScript, defined in the previous chapter, to load scripts one by one, in sequence: This code can be made bit shorter with arrow functions: Here each loadScript call returns a promise, and the next .then runs when it resolves. Then it initiates the loading of the next script. So scripts are loaded one after another. We can add more asynchronous actions to the chain. Please note that the code is still “flat” — it grows down, not to the right. There are no signs of the “pyramid of doom”. Technically, we could add .then directly to each loadScript, like this: This code does the same: loads 3 scripts in sequence. But it “grows to the right”. So we have the same problem as with callbacks. People who start to use promises sometimes don’t know about chaining, so they write it this way. Generally, chaining is preferred. Sometimes it’s ok to write .then directly, because the nested function has access to the outer scope. In the example above the most nested callback has access to all variables script1, script2, script3. But that’s an exception rather than a rule. class Thenable { constructor(num) { this.num = num; then(resolve, reject) { alert(resolve); // function() { native code } // resolve with this.num2 after the 1 second setTimeout(() => resolve(this.num 2), 1000); // () new Promise(resolve => resolve(1)) .then(result => { return new Thenable(result); // (*) .then(alert); // shows 2 after 1000ms

Bigger example: fetch

In frontend programming, promises are often used for network requests. So let’s see an extended example of that. We’ll use the fetch method to load the information about the user from the remote server. It has a lot of optional parameters covered in separate chapters, but the basic syntax is quite simple: This makes a network request to the url and returns a promise. The promise resolves with a response object when the remote server responds with headers, but before the full response is downloaded. To read the full response, we should call the method response.text(): it returns a promise that resolves when the full text is downloaded from the remote server, with that text as a result. The code below makes a request to user.json and loads its text from the server: The response object returned from fetch also includes the method response.json() that reads the remote data and parses it as JSON. In our case that’s even more convenient, so let’s switch to it. We’ll also use arrow functions for brevity: Now let’s do something with the loaded user. For instance, we can make one more request to GitHub, load the user profile and show the avatar: The code works; see comments about the details. However, there’s a potential problem in it, a typical error for those who begin to use promises. Look at the line (): how can we do something after* the avatar has finished showing and gets removed? For instance, we’d like to show a form for editing that user or something else. As of now, there’s no way. To make the chain extendable, we need to return a promise that resolves when the avatar finishes showing. Like this: That is, the .then handler in line () now returns new Promise, that becomes settled only after the call of resolve(githubUser) in setTimeout (*). The next .then in the chain will wait for that. As a good practice, an asynchronous action should always return a promise. That makes it possible to plan actions after it; even if we don’t plan to extend the chain now, we may need it later. Finally, we can split the code into reusable functions:

Summary

If a .then (or catch/finally, doesn’t matter) handler returns a promise, the rest of the chain waits until it settles. When it does, its result (or error) is passed further. Here’s a full picture:

new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000); // (*)

}).then(function(result) { // (**)

  alert(result); // 1
  return result * 2;

}).then(function(result) { // (***)

  alert(result); // 2
  return result * 2;

}).then(function(result) {

  alert(result); // 4
  return result * 2;

});
Example:

Follow the lesson from Microsoft Web-Dev-For-Beginners course

Tags: promise