DEV Community

Cover image for In trouble with promises? Don't worry here's your saviour
Mohammed khalid
Mohammed khalid

Posted on

In trouble with promises? Don't worry here's your saviour

This article is just an extremely simple intro to ES6 promises to make it clearer, and I hope that at the end of this article, I have helped you to be more familiar with JavaScript promises.

Promises in JavaScript is just like the promises in our real life, Promises in our real-life have two possibilities: fulfilled or unfulfilled. That's the same thing in JavaScript promises, there're three possibilities:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected(unfulfilled): meaning that the operation failed.

In JavaScript, Promises are used to handle asynchronous operations.


A promise can be created using Promise constructor

Alt Text
"Promise constructor takes only one argument, a callback function, this callback function takes two arguments, resolve and reject, and if everything went well then call resolve. If desired operations do not go well then call reject"

  • Promises can be consumed by registering functions using .then and .catch methods.

  • then() is invoked when a promise is either resolved or rejected. 

  • catch() is invoked when a promise is either rejected or some error has occurred in execution.

Alt Text


Example

Alt Text
"Expected output - He didn't wash his hand"


Promise methods

  • Promise.reject()
    "Promise.reject returns a rejected promise"

  • Promise.resolve()
    "Promise.resolve returns a resolved promise"

  • Promise.all()
    "Promise.all takes an array of promises. Then it gets resolved when all the promises get resolved or reject with the reason of the first passed promise that rejects"

Alt Text
"Expected output - (3) ["Post 1 is done", "Post 2 is done", "Post 3 is done"]"

  • Promise.race() "Promise.race is just like promise.all except for it'll return as soon as the first one is completed instead of waiting for everything to complete"

Alt Text
"Expected output - Post 1 is done"

  • Promise.allSettled() "Promise.allSettled returns a Promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describes the outcome of each promise"

Alt Text
"Expected output - (3) [{…}, {…}, {…}] 0: {status: "fulfilled", value: "Post 1 is done"} 1: {status: "fulfilled", value: "Post 2 is done"} 2: {status: "fulfilled", value: "Post 3 is done"}"

I hope I have helped you to be more familiar with JavaScript promises. and if you want to go deeper I recommend these sources for you

https://medium.com./javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261

https://medium.com./better-programming/understanding-promises-in-javascript-13d99df067c1

Top comments (0)