Promises in JavaScript

Anas Aqeel

Anas Aqeel

· 3 min read
JavaScript Promises

Promises in JavaScript

With Promises, we can organize the sequence of our code in a slightly easier-to-maintain way. A Promise is a special object that connects code that needs to produce a result and the code that needs to use this result in the next step.

When we create a Promise, we give it a function. In the following example, we use a convention that we have seen a lot; we are creating a function on the spot. So, inside the argument list we are defining the function, often done using arrow functions as well. This function needs two parameters, and these parameters are callbacks. We have called them resolve and reject here.

You can call these parameters anything you want, but resolve or res and reject or rej are most common.

When resolve() is called, the Promise is presumed to be successful and whatever is between the arrows is returned and used as input for the then method on the Promise object. If reject() is called, the Promise failed and the catch() method on the Promise object (if present) is executed with the argument of the reject() function.

We first create a Promise. When creating a Promise , we don't know what the value of the Promise is going to be. This value is whatever is sent as an argument to the resolve function. It is a sort of placeholder.

So when we call then on the Promise, we basically say: figure out what the value of the Promise is, and when you know, execute one function if the Promise was resolved or a different function if it was rejected. When a Promise is neither resolved nor rejected, we say that the Promise is pending.

then() is a Promise itself, so when it returns we can use the result for the next then() instance. This means we can chain the then() instances, which can look like this:

This will log:

The resolve functions are implemented with an arrow function. The return statement is the value input for the next function. You can see that the last block is a catch() function. If any of the functions were to result in a rejection and the Promise were therefore rejected, this catch() block would be executed and print whatever the reject() function sent to the catch() method. For example:

This will just log oops… because the first Promise was rejected instead of resolved. This is great for creating asynchronous processes that need to wait till another process is complete. We can try to do a certain set of actions and when something goes wrong, use a catch() method to deal with it.

Anas Aqeel

About Anas Aqeel

I’m currently working Frontend Development having an experience of building Web applications with JavaScript / React-JS / Node-JS and some other cool libraries and frameworks. I’m currently learning web3 technologies such as Solidity, Ether-JS and web3.

Copyright © 2025 Coding Hub. All rights reserved.
Made by Anas-Aqeel
coding~hub