Forem

Cover image for ES6: Promises
Vincent Tong
Vincent Tong

Posted on

ES6: Promises

What are promises:

With the introduction of ES6 came Promises. They are an object class that represents a value depending on a successful/failed completion of an asynchronous operation.

As the name implies, using promise is akin to making a commitment to performing some operation or providing some value in the future.

There are two possible outcomes to a promise: either it is successful and it resolves or it fails and is rejected.

Why use promises:

  • similar to using success & error callbacks, but in a much cleaner way.

  • prevents callback hell (when you have so many nested callbacks, it's hard to keep track of it all). This is done through the use of .then() and .catch(). more on them later.

Syntax:

As briefly mentioned earlier, a promise object takes in a callback function with two parameters: resolve & reject.

const examplePromise = new Promise((resolve, reject) => {

});
Enter fullscreen mode Exit fullscreen mode

Now, within the callback function, you would define what the promise is.

const examplePromise = new Promise((resolve, reject) => {
let grade = 100;

if (grade >= 70) {
 resolve("passed");
} else {
 reject ("failed");
}

});
Enter fullscreen mode Exit fullscreen mode

As you can see, the resolve argument will be called if the condition met is true and the reject will be called if it is false. But what exactly do the resolve and reject do?

.then() & .catch()

This is where .then() and .catch() come into play.

.then() will invoke if the promise resolves/rejects.
.catch() will invoke if the promise rejects.

With our newly created promise, we can invoke & chain these methods like so:

examplePromise
.then((message) => console.log("you " + message))
.catch((message) => console.log("you " + message));
Enter fullscreen mode Exit fullscreen mode

.then() passes in a callback for when the promise resolves and also an optional callback for if the promise rejects.

.catch() only passes in a callback for when the promise rejects.

The callbacks within the .then() & .catch() will pass in the same arguments as the respective resolve and reject calls. As you may have guessed, since our grade was set at 100, it will invoke the resolve, which in turn invokes our .then() to log to the console:

"you passed"

As mentioned before, .then() takes in a resolve callback but can ALSO take a reject callback. does that sound familiar? It's just like a promise. That is because every call to .then() returns a new promise, which is why we can chain multiple .then() calls to it.

Promise Methods

  • .all() - Promise.all() takes in an iterable amount of promises. Once each of those promises resolves, it will return a single promise that resolves to an array of the results of those inputted promises.[1]

If any of the inputted promises should reject, Promise.all() asynchronously rejects and returns the value of the promise that rejected, regardless of if the other input promises have resolved.

  • .allSettled() - takes in an iterable amount of promises and will return an array of their outcomes, regardless of whether or not the resolved or rejected.

  • .any() - takes in an iterable amount of promises and will return a promise that resolves at the first instance of one of the input promises being fulfilled/resolved.

  • .race() - similar to .any() but will return at the first instance of any of the input promises being resolved or rejected.

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (1)

Collapse
 
ahmad_butt_faa7e5cc876ea7 profile image
Ahmad

thanks , thats helpful! especially the callback signature

plus theres certain points where you caint use async/await . For example, within Reacts useEffect method

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay