Chaining
Chaining is what is so great about promises.
Since Promises capture the notion of asynchronicity in an object, we can chain them, map them, have them run in parallel or sequential, all kinds of useful things. Code like the following is very common with Promises:
getSomeData
is returning a Promise, as evidenced by the call to then()
, but the result of that first then must also be a Promise, as we call then()
again (and yet again!) That’s exactly what happens, if we can convince then()
to return a Promise, things get more interesting.
then() always returns a Promise
then()
takes 2 arguments, one for success, one for failure (or fulfill and reject, in promises-speak), each will return a promises.
Transforming values
Chaining promises is useful for transforming values, each .then(func)
return a promise resolved with the returned value of func
. For example:
As a practical example, chaining of promises is great for processing data from an HTTP request: get the content - parse the content - filter the content.
Example with the GitHub API
Here is an example using the GitHub API and promises, that will display the list of repositories of the most followed GitHub user.
For this example, we'll consider the method get(url)
as doing the HTTP GET method to url and returning a promise that'll be resolved with the plain text content.
Then we can easily call the method getReposMostFollowedUser()
that will return a promise.
Last updated
Was this helpful?