Simple explanation of Javascript Promises

in #javascript7 years ago

Promises are one of the least understood concepts in Javascript. New Javascript developers as well as some experienced ones find the concept of promises difficult. But there are good resources that manage to explain promises very well. The Mozilla Developer's Network is one of those sites that gives very good explanations and examples of promises:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

Based on the MDN page above, a Promise is an object the represents the eventual completion or failure of an async operation.

A promise can be in either of the following states:

  • pending
  • fulfilled
  • rejected

The pending state implies the promise's final state is still pending and it is yet to be fulfilled or rejected. The fulfilled state implies the promise has been fulfilled where as the rejected state implies the opposite.

Creating a promise involves instantiating an object from the Promise constructor function:

new Promise((resolve, reject)) {});

The Promise object has the following methods

Promise.all()
Promise.prototype.catch()
Promise.prototype.then()
Promise.race()
Promise.reject()
Promise.resolve()

The Promise constructor accepts two arguments, 'resolve' and 'reject' that are also functions. Parameters are passed into
these functions to be resolved or rejected.![code.png]

Using the promise prototype's methods 'then' and 'catch' we can do whatever we want with the resolved or rejected data we get from the promise. The 'then()' method accepts a success function that also has an argument that holds the resolved value of the promise. It is called whenever a promise gets fulfilled. The 'catch()' method accepts a failure function that also has an argument that holds the rejected value of the promise. It is called when the promise is rejected.

I will try simulate a delayed response using Javascript's setTimeout function and see how we can resolve and reject a promise based on a condition I am going to set.

If a number that is passed into the following 'evenResolver' function is even, resolve it and if it is odd reject it with a reason.

If I make the call evenResolver(20), I will get the number 20 printed to the console. But if I pass
21 to the evenResolver, the promise would be rejected with the reason 'The number you supplied is odd.'.

Checkout the MDN for more about promises. I hope the above was a little bit helpful in making promises easier for you. I will discuss about chaining promises in my next article.

Coin Marketplace

STEEM 0.20
TRX 0.12
JST 0.029
BTC 60320.14
ETH 3373.37
USDT 1.00
SBD 2.51