Share

What is Promise?

By: Fatima Zahra Khan.

What is Promise in JavaScript? And how to use it.

The promise is an object which returns the completion or a failure of an asynchronous task. Visit Using Promise to learn about its usage.

About JS Promise

A Promise is a stand-in for a value that isn’t always known at the time the promise is made. It enables you to link handlers to the ultimate success or failure value of an asynchronous action. This enables asynchronous methods to return results similarly to synchronous methods: rather than delivering the result right away, the asynchronous function returns a promise to provide the result at a later time.

Three States of Promise

  • When it is neither accomplished nor rejected, it is at initial pending state.
  • When it is accomplished, it is at fulfilled state.
  • When it is not accomplished, it is at rejected state.

A pending promise can either be fulfilled with value or rejected with a justification, depending on its final outcome (error). The corresponding handlers queued up by a promise’s then method are called when either of these scenarios occurs. There won’t be a race condition between an asynchronous operation finishing and its handlers being attached if the promise has already been fulfilled or refused when the handler is attached.

If a promise is either kept or broken, but not both, it is considered to be settled.

If a promise is resolved, it indicates that it has been “locked-in” to match the outcome of another promise and that further resolving it or rejecting it will have no further effect. More information on promise terminology may be found in the States and destinies document from the initial Promise proposal. Generally speaking, “resolved” promises are synonymous with “fulfilled” promises, but as “States and Fate” shows, resolved promises can also be pending or rejected. For instance:

new Promise((resolveParent) => {
  resolveParent(
    new Promise((resolveChild) => {
      setTimeout(resolveChild, 1000);
    })
  );
});

Because resolveParent is called synchronously, this promise is already resolved when it is formed, but because it is resolved with another promise, it won’t be fulfilled until one second after the inner promise is fulfilled. In actuality, only the fulfilment or rejection of the “resolution” is visible; the “resolution” is frequently carried out invisibly behind the scenes.

Other languages, like Scheme, offer features for lazy evaluation and delaying a calculation that they also refer to as “promises.” Callback functions allow you to chain together already-running processes in JavaScript by using promises. Consider using a function with no arguments, such as f = () => expression, to generate the expression to be lazily evaluated, and f() to evaluate the expression instantly, if you want to do so.