All original content is created in Ukrainian. Not all content has been translated yet. Some posts may only be available in Ukrainian.Learn more

The structure of Promise (JavaScript) and how to work with it

Post cover: The structure of Promise (JavaScript) and how to work with it
This content has been automatically translated from Ukrainian.
Promise is an object that represents the result of an asynchronous operation. They allow working with deferred results without nested callbacks, making the code more readable. Earlier, I wrote a small post about what a Promise is. But now let's look at the structure and some methods.

What the Structure of a Promise Looks Like

Promise is created using the constructor new Promise(), which takes a function with two arguments: resolve and reject. This is the structure to remember. Let's consider an example:
const promise = new Promise((resolve, reject) => {
  const success = Math.random() > 0.5;
  
  setTimeout(() => {
    if (success) {
      resolve("Operation completed successfully");
    } else {
      reject("An error occurred");
    }
  }, 1000);
});
This code creates a promise that after one second (timeout 1000) either resolves (resolve) with the string "Operation completed successfully" or rejects (reject) with an error message. In other words, we created an emulation of a response success, waited a second, and got a result that depended on our random value in success.

Working with Promises

Promise has methods .then(), .catch(), and .finally() for handling results.
promise
  .then(result => {
    console.log("Success:", result);
  })
  .catch(error => {
    console.log("Error:", error);
  })
  .finally(() => {
    console.log("Operation completed");
  });
Here .then() receives the value from resolve, .catch() handles the error from reject, and .finally() always executes, regardless of the result. These methods are also worth remembering.

Promise Chains

The .then() method returns a new Promise, allowing for sequential (chained) execution.
new Promise(resolve => resolve(10))
  .then(num => num * 2)
  .then(num => num + 5)
  .then(result => console.log("Result:", result));
Here the initial value 10 is multiplied by 2, 5 is added, and the result is 25.

Promise.all, Promise.race, and Promise.any

The Promise.all() method waits for the execution of all passed promises.
Promise.all([
  new Promise(resolve => setTimeout(() => resolve("First"), 1000)),
  new Promise(resolve => setTimeout(() => resolve("Second"), 2000))
]).then(results => console.log("All completed:", results));
And Promise.race() returns the first completed promise. This method is easy to remember by the name race - whoever finishes first wins.
Promise.race([
  new Promise(resolve => setTimeout(() => resolve("First"), 1000)),
  new Promise(resolve => setTimeout(() => resolve("Second"), 500))
]).then(result => console.log("First completed:", result));
Promise.any() is a method that takes an array of promises and returns the first successfully completed promise. If all promises are rejected, it returns an AggregateError.
const p1 = new Promise((_, reject) => setTimeout(() => reject("Error 1"), 1000));
const p2 = new Promise(resolve => setTimeout(() => resolve("Success 2"), 2000));
const p3 = new Promise(resolve => setTimeout(() => resolve("Success 3"), 3000));

Promise.any([p1, p2, p3])
  .then(result => console.log("First successful result:", result))
  .catch(error => console.log("All promises rejected:", error));
What happens in the example:
  1. p1 is rejected after 1 second.
  2. p2 is successfully completed after 2 seconds.
  3. Promise.any() returns p2 since it was the first successful one.
  4. If all promises are rejected, an AggregateError will be returned containing all errors.
This method is useful when you need to get the first successful result, ignoring the failures.

This post doesn't have any additions from the author yet.

09 Dec 14:50

[Fix] No such file or directory @ rb_sysopen - tmp/pids/server.pid

meme code
meme code@memecode
What you need to know to build a successful freelance career in IT
23 Dec 16:03

What you need to know to build a successful freelance career in IT

meme code
meme code@memecode
Virtual cloud server: what it is and what makes it special
03 Jan 10:58

Virtual cloud server: what it is and what makes it special

meme code
meme code@memecode
[Fix] Heroku / SearchBox addon - indexing error "The client is unable to verify that the server is Elasticsearch"
31 Jan 13:09

[Fix] Heroku / SearchBox addon - indexing error "The client is unable to verify that the server is Elasticsearch"

meme code
meme code@memecode
06 Feb 15:31

Fix error [DEPRECATION] #adapters is deprecated. Use #profiles instead. (Codecov / docile)

meme code
meme code@memecode
What is a Promise in JavaScript and how to quickly understand its essence?
18 Feb 11:01

What is a Promise in JavaScript and how to quickly understand its essence?

meme code
meme code@memecode
What is Memoization (examples in Ruby and Ruby on Rails)?
20 Feb 18:16

What is Memoization (examples in Ruby and Ruby on Rails)?

meme code
meme code@memecode
What is debounce in JavaScript and why is it important?
21 Mar 16:39

What is debounce in JavaScript and why is it important?

meme code
meme code@memecode
What is CFB (Cipher Feedback)?
21 Mar 16:53

What is CFB (Cipher Feedback)?

meme code
meme code@memecode
What is XOR and how does it work?
21 Mar 17:05

What is XOR and how does it work?

meme code
meme code@memecode
Embedded programming: what it is and how to get started
24 Mar 16:48

Embedded programming: what it is and how to get started

meme code
meme code@memecode
Pessimistic Lock in Rails: what it is and when to use it. What are the alternatives?
31 Mar 17:45

Pessimistic Lock in Rails: what it is and when to use it. What are the alternatives?

meme code
meme code@memecode