Loading [Contrib]/a11y/accessibility-menu.js

JavaScript promises, mastering the asynchronous

Magus
282.7K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

How can the Promise class help us? First off, everyone uses it because it is now the standard way to deal with asynchronous code... so we have to use it. Following the standard is always the best thing to do. Now that we know that, here is a simple example of how to use a promise.

As you shown above, you can use the resolve function to fullfil the promise. The then function binds a callback to the promise and you can use the data given to the resolve function.

You can bind multiples callbacks:

The reject function is used to trigger an error. When you use then, you can give 2 functions. The first function is used when the promise exits successfully. The second function is used when the promise encounters an error.

You can still bind multiple then methods:

You can call resolve and reject multiple times, but this is useless. Once a promise is finished, it can't restart.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content