Why We Need Promise in JS?

When Your life messed up because of some problem that time all you need is promise from your friend that help you out from that difficult situation. Same way in JavaScript when we find ourselves in callback hell , we need promise that helps us out from call back hell.

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.(MDN definition)

When promise called its has 3 outcomes : 1)resolve 2)reject 3)Pending

1)Resolve: when promise is resolved then its means that request that we made from promise is done now we can use then to perform next operation on return resolved object.

image.png

Syntax: Promise.resolve(value);

Example:

const p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('AppDividend'); }, 1000); });

p1.then(values => { console.log(values); });

Output: AppDividend

2)Reject : when promise is reject then its means that request that we made from promise is rejected now we can use then to perform next operation on return reject object.

Syntax: const p1 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars setTimeout(() => { reject(new Error('Promise failed')); }, 1000); });

p1.then(error => { console.log(error); });

Output: Error: promise failed

3)Pending:

when our request is between resolve and reject condition that we call it is in Pending state. Once a promise has been called, it will start in a pending state. This means that the calling function continues executing, while the promise is pending until it resolves, giving the calling function whatever data was being requested.