Skip to main content

Command Palette

Search for a command to run...

Promises made by JavaScript

Updated
5 min read

JavaScript provides us with a special function type, which has more patience than our regular functions. Today we shall use startup world(basically funding) to understand the promises and their methods a little better.

  • In a business convention, 4 judges judge the promises made by the startUps and select one of the proposition(promise) to invest in.

  • The most common way to initiate a promise is given by the syntax below:

const prom1 = new Promise((res, rej) => res("500M subscribers unlocked"));

A promise is a function that can have 3 executional states, unlike a function that simply executes when called and runs without any waiting.

  1. Pending: Still being executed

  2. Fulfilled: The function has run and returned the intended data successfully

  3. Rejected: The function has failed to work in intended manner.

Hope you are comfortable with reading pages, because the analogies about to be presented are gonna blow your socks off.

Promises and their functions

  • Promises offer us some inbuilt methods such as .all(), .race(), .allSettled(), .any().

  • They take a number of promises and work based on their nature that is further discussed.

Analogy

  • There is an startup convention and it is a chance for up and coming business people to interact(receive funding) with other business experts.

  • Hence an up and coming startUp promised, is supposed to present to present to a panel of more experienced founders. The requesting startUp promised had made a few promises on a few deliverables. Deliverables such as

    • millions in sales,

    • A website capable enough to handle hundred thousands of visitors,

    • Presence across the globe

  • The panel corresponding to their quirks, have various criteria for accepting a mentee. Those criteria is the main topic of our discussion today.

    • .all(): Is the Old VC executive.

    • .race(): Is the young investor, she values speed and has only one slot to fill.

    • .any(): The cool tech bro. He is only concerned with one promise that works.

    • .allSettled(): The wise old sage of the valley, he offers guidance regarding all the promises made.

  • The panel has 2 ways .then() and .catch() to verify the state of promises, .then() receives the promised delivered.

  • .catch() receives the error and print those.

  • .then() receives an array of all the delivered promises.

Promise.all([...promises])

  • Promise.all() is the Old VC executive, Mr. S. Hark, wearing a 3 piece suit and adorned with expensive watches and rare shoes.

  • He expects each one of the promise to be delivered in a successful manner(all resolved or fulfilled).

Promise.all([
    Promise.resolve("Sales Checked"),
    Promise.resolve("Website capable Enough"),
    Promise.reject("Global Presence Not delivered")
])
.then((data) => console.log(data))
.catch((error) => console.log(error))

//Global Presence Not delivered: catch block prints the error  
  • Success: Returns an array of results only after all promises have fulfilled.

  • Failure: Rejects immediately if any promise rejects.

Promise.race()

  • Promise.race() is a new investor, Mrs. F. Ast, she is a sharp woman and knows the value of things.

  • She values her time, and hence checks the fastest of the promise, the startUp promised, and makes up her mind based on that decision only.

  • For example, if she first verified the sales and that promise is a success, then she would invest, even if it fails she would invest in that one only.

Promise.race([
   new Promise((res, rej) => setTimeout(() => {res("sales done")}, 1000)),
   new Promise((res, rej) => setTimeout(() => {rej("website not capable enough")}, 500)),
   new Promise((res, rej) => setTimeout(() => {res("Global Presence achieved")}, 5000)),
])
.then((data) => console.log(data))
.catch((error) => console.log(error))

//website not capable enough as 2nd promise exited the pending state first
  • Success/Failure: Settles as soon as the very first promise settles, with that result or error.

Promise.any()

  • Promise.any() is the cool hip tech bro. He wears a hoodie and focuses on the resolved only and hence pivots on the basis of that. The first

  • Promise.any() takes an array of promises and returns the first promise to be resolved only.

Promise.any([
   new Promise((res, rej) => setTimeout(() => {res("sales done")}, 1000)),
   new Promise((res, rej) => setTimeout(() => {rej("website not capable enough")}, 500)),
   new Promise((res, rej) => setTimeout(() => {rej("Global Presence achieved")}, 5000)),
])
.then((data) => console.log(data))
.catch((error) => console.log(error)) 
//sales done: As the first promise to resolve successfully 
  • Success: Returns the value of the first promise to succeed.

  • Failure: Rejects only if all promises reject (returns an AggregateError).

Promise.allSettled()

  • Promise.allSettled() is the old wise sage of the silicon valley. He is the most patient and kind of all. He just provides the status and reason of all the promises provided.

  • This method waits for all promises to finish, regardless of whether they succeeded or failed. It never "fails" as a whole; it just gives you a report on everything that happened.

Promise.allSettled([
   new Promise((res, rej) => setTimeout(() => {res("sales done")}, 1000)),
   new Promise((res, rej) => setTimeout(() => {rej("website not capable enough")}, 500)),
   new Promise((res, rej) => setTimeout(() => {rej("Global Presence achieved")}, 5000)),
])
.then((data) => console.log(data))
.catch((error) => console.log(error))

/*[
  { status: 'fulfilled', value: 'sales done' },
  { status: 'rejected', reason: 'website not capable enough' },
  { status: 'rejected', reason: 'Global Presence achieved' }
]*/ 
  • Success: Returns an array of objects describing the outcome of each promise.

  • Failure: Never rejects (unless the input itself is invalid).

Conclusion

The various Promises function provide various ways to deal with multiple promises. Some of them need all to succeed, some want one, some offer guidance without the regard of success/failure.
The promises offer us an extra component of time to play around.

I would extend my gratitude towards team of Hitesh Choudhary, Akash Kadlag, Piyush Garg.