Promises In JavaScript Made Simple

The simplest explanation of a ‘Promise’ in JavaScript can be referenced to a promise in real life. When creating a new promise, the promise constructor takes 2 arguments ‘resolve’ and ‘reject.’  Resolve means fulfilling the promises set forth. In other words, completing what you said you’re going to do. Reject means promise is not fulfilled, in other words not completing what was set forth. The code below shows how easy it is to create a new promise.

When the promise is executed we will get back a result. If the promise is successful it will return a ‘resolve,’ then we can utilize the Promise.then() function.

In the code below, we can pass in an argument, ‘fromResolve,’ to the Promise.then() function. This argument will show us the status of the resolve.

If the promise is not fulfilled we can then catch the result in a function called Promise.catch().

The code above showed that we chain the Promise.catch() after the Promise.then() and pass in an argument of ‘fromReject.’

Nested Promises

Let me add more complexity, in the code below I’ve created 3 different promises. We can then nest the promises together based on different rules and get the desired result.

Let say you don’t want to nest the promises and you don’t want to wait for one to finish and the second to start. We then can use the Promise.all() method to accomplish this objective and once they are all done it returns a result.

Promise Race

Another use case would be if you’re trying to pull the same data from three different servers. You could use the Promise.race() method to accomplish this. Below is the code example.

Conclusion

Now, you know what a promise is and how to create one in JavaScript. Give it a try! I hope this gave you a better and more simple understanding of Promises in JavaScript.