Deep deep deep into Promises

What is a Promise?

How to create a Promise?

  • state — initially “pending”, then changes to either “fulfilled” when resolve is called or “rejected” when reject is called.
  • result — initially undefined, then changes to value when resolve(value) is called or error when reject(error) is called.
https://rollettpro.com/image/apex/action-function-not-getting-executed.png

How to get actual data from ‘promise’?

Promise static methods

  • Promise.all(iterable) — wait for all promises to be resolved, or for any to be rejected.
  • Promise.allSettled(iterable) — wait until all promises have settled (each may resolve or reject).
  • Promise.any(iterable) — takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise.
  • Promise.race() — wait until any of the promises is fulfilled or rejected.
  • Promise.reject(reason) — returns a new Promise object that is rejected with the given reason.
  • Promise.resolve() — returns a Promise object that is resolved with a given value. If the value is a promise or “thenable” object, that promise is returned; otherwise, the returned promise will be fulfilled with the value.
Promise.resolve(5) -> returns promise<fulfilled>(5)Promise.resolve(Promise.resolve(5)) -> returns promise<fulfilled>(5)

This is where the magic begins

  1. Promise.resolve returns a fulfilled promise for plain values.
  2. Promise.resolve returns a fulfilled promise when the value passed is a fulfilled promise.
  3. Resolve function passed to the executor returns a fulfilled promise for plain values.
  4. Resolve function passed to the executor returns a pending promise when the value passed is a fulfilled promise.
  5. The delayed result of the resolve function passed to the executor is a fulfilled promise when the value passed is a fulfilled promise.

What conclusions can we draw from this?

  1. Promise.resolve and resolve function work the same way for plain values. Both returns fulfilled promises.
  2. Promise.resolve and resolve functions work differently when a promise is passed as an argument. Promise.resolve returns the same promise passed as an argument when resolve works in some strange way.
  3. resolve returns pending promise for any promised values regardless of their state. And may change the returned promise’s state in some async way.

In conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store