How to Chain JavaScript Promises – Intro Tutorial to JavaScript Promises

How to Chain JavaScript Promises – Intro Tutorial to JavaScript Promises

What are JavaScript promises?

In it’s new ECMA 6 version, JavaScript allows you to create a new type of object called a Promise. Promises are used for asynchronous or deferred computations, and can be an alternative to the usual callback approach.

Promises can be used both on the browser (support is still not universal but it’s getting there) or in Node.js apps.

Promises can either resolve or get rejected. Inside of a promise, you are free to call the “resolve” and “reject” method whenever you see fit.

Example of a promise:

What’s wrong with using just callbacks?

Nothing, but there are times (specially on Node.js apps) when you are performing multiple operations and you need to wait for the result of one in order to move to the next. In these cases you enter what’s called the “callback hell”, when you have several callbacks inside of other callbacks.

For example, you need to do the following: read a MongoDB collection, call an external API, call some other API, save some data in MongoDB. In each step you need the result of the previous step. Using callbacks can make your code very messy.

This is an example when using JavaScript promises and chaining them together would make things easier

How do you chain JavaScript promises?

The following example shows how you can chain JavaScript native promises using the then keyword.

Imagine you have three methods that do asynchronous operations (example: Ajax calls, calls to API, Mongo operations, writing to disk, etc). You want to call “secondMethod” when “firstMethod” completes, and when “secondMethod” completes you then want to call “thirdMethod”.

See how easy this becomes with promises:

Learn JavaScript ES6 online at your own pace

Check out the online course Learn JavaScript ES6 on Zenva Academy for more information.

Tutorials on game, web and mobile app development