DEV Community

Cover image for Promises in JavaScript and React Native: Creation, Usage, and Common Scenarios
Ajmal Hasan
Ajmal Hasan

Posted on

Promises in JavaScript and React Native: Creation, Usage, and Common Scenarios

Handling asynchronous tasks is essential in JavaScript, especially in environments like React Native where data fetching, animations, and user interactions need to work seamlessly. Promises provide a powerful way to manage asynchronous operations, making code more readable and maintainable. This blog will cover how to create and use promises in JavaScript, with practical examples relevant to React Native.


What is a Promise?

A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation. It allows us to handle asynchronous code in a more synchronous-looking way, avoiding the classic “callback hell.” Promises have three states:

  • Pending: The initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Creating a Promise

To create a promise, we use the Promise constructor, which takes a single function (the executor function) with two parameters:

  • resolve: Call this function to fulfill the promise when the operation completes successfully.
  • reject: Call this function to reject the promise if an error occurs.

Example: Creating a Basic Promise

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const success = true; // Simulating success/failure
      if (success) {
        resolve({ data: "Sample data fetched" });
      } else {
        reject("Error: Data could not be fetched.");
      }
    }, 2000); // Simulate a 2-second delay
  });
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We create a promise that simulates fetching data with a setTimeout.
  • If the success variable is true, we call resolve() with some data; otherwise, we call reject() with an error message.

Using Promises with .then(), .catch(), and .finally()

Once a promise is created, we can handle its outcome using:

  • .then() to handle successful resolutions,
  • .catch() to handle errors, and
  • .finally() to execute code after the promise settles, regardless of outcome.

Example: Handling a Promise

fetchData()
  .then((result) => console.log("Data:", result.data)) // Handle success
  .catch((error) => console.error("Error:", error))    // Handle failure
  .finally(() => console.log("Fetch attempt completed")); // Finalize
Enter fullscreen mode Exit fullscreen mode

In this example:

  • .then() is called if the promise is resolved, printing the data.
  • .catch() handles any errors that occur if the promise is rejected.
  • .finally() runs regardless of whether the promise is resolved or rejected.

Practical Use Cases for Promises in React Native

1. Fetching Data from an API

In React Native, data fetching is a common asynchronous task that can be efficiently managed with promises.

function fetchData(url) {
  return fetch(url)
    .then(response => {
      if (!response.ok) throw new Error("Network response was not ok");
      return response.json();
    })
    .then(data => console.log("Fetched data:", data))
    .catch(error => console.error("Fetch error:", error));
}

// Usage
fetchData("https://api.example.com/data");
Enter fullscreen mode Exit fullscreen mode

Use Case: Fetching data from REST APIs or other network requests, where we need to handle both successful responses and errors.


2. Using Promises for Sequential Async Operations

Sometimes, one asynchronous task depends on another. Promises make it easy to chain operations in sequence.

function authenticateUser() {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ userId: 1, name: "John Doe" }), 1000);
  });
}

function fetchUserProfile(user) {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ ...user, profile: "Profile data" }), 1000);
  });
}

// Chain promises
authenticateUser()
  .then(user => fetchUserProfile(user))
  .then(profile => console.log("User Profile:", profile))
  .catch(error => console.error("Error:", error));
Enter fullscreen mode Exit fullscreen mode

Use Case: Useful for logging in a user and then fetching profile data based on their identity.


3. Handling Multiple Promises with Promise.all()

If you have multiple independent promises that can be executed in parallel, Promise.all() allows you to wait for all of them to resolve or for any of them to reject.

const fetchPosts = fetch("https://api.example.com/posts").then(res => res.json());
const fetchComments = fetch("https://api.example.com/comments").then(res => res.json());

Promise.all([fetchPosts, fetchComments])
  .then(([posts, comments]) => {
    console.log("Posts:", posts);
    console.log("Comments:", comments);
  })
  .catch(error => console.error("Error fetching data:", error));
Enter fullscreen mode Exit fullscreen mode

Use Case: Fetching multiple resources concurrently, such as fetching posts and comments from separate API endpoints.


4. Racing Promises with Promise.race()

With Promise.race(), the first promise that settles (resolves or rejects) determines the result. This is helpful when you want to set a timeout for a long-running task.

const fetchData = fetch("https://api.example.com/data");
const timeout = new Promise((_, reject) => setTimeout(() => reject("Request timed out"), 3000));

Promise.race([fetchData, timeout])
  .then(response => console.log("Fetched data:", response))
  .catch(error => console.error("Error:", error));
Enter fullscreen mode Exit fullscreen mode

Use Case: Setting a timeout for network requests, so they don’t hang indefinitely if the server is slow or unresponsive.


5. Using Promise.allSettled() to Handle Mixed Outcomes

Promise.allSettled() waits for all promises to settle, regardless of whether they resolve or reject. This is useful when you need the results of all promises, even if some fail.

const promises = [
  Promise.resolve("Success 1"),
  Promise.reject("Error 1"),
  Promise.resolve("Success 2"),
  Promise.reject("Error 2")
];

Promise.allSettled(promises).then(results => {
  results.forEach((result, index) => {
    if (result.status === "fulfilled") {
      console.log(`Promise ${index + 1} succeeded with value:`, result.value);
    } else {
      console.error(`Promise ${index + 1} failed with reason:`, result.reason);
    }
  });
});
Enter fullscreen mode Exit fullscreen mode

Use Case: Useful when executing multiple requests where some may fail, such as fetching optional data sources or making multiple API calls.


Advanced Techniques: Converting Callbacks to Promises

Older codebases or certain libraries might use callbacks instead of promises. You can wrap these callbacks in promises, converting them to modern promise-based functions.

Example: Wrapping a Callback in a Promise

function fetchDataWithCallback(callback) {
  setTimeout(() => {
    const success = true;
    if (success) {
      callback(null, "Data fetched successfully");
    } else {
      callback("Error fetching data", null);
    }
  }, 1000);
}

function fetchDataPromiseWrapper() {
  return new Promise((resolve, reject) => {
    fetchDataWithCallback((error, data) => {
      if (error) reject(error);
      else resolve(data);
    });
  });
}

// Using the wrapped promise
fetchDataPromiseWrapper()
  .then(data => console.log("Data:", data))
  .catch(error => console.error("Error:", error));
Enter fullscreen mode Exit fullscreen mode

Use Case: This technique allows you to work with legacy callback-based code in a promise-friendly way, making it compatible with modern async/await syntax.


Summary

Promises are powerful tools for managing asynchronous operations in JavaScript and React Native. By understanding how to create, use, and handle promises in various scenarios, you can write cleaner and more maintainable code. Here’s a quick recap of common use cases:

  • API Requests: Fetching data from a server with error handling.
  • Chaining Operations: Executing dependent tasks in sequence.
  • Parallel Operations: Running multiple promises concurrently with Promise.all().
  • Timeouts and Racing: Limiting request duration with Promise.race().
  • Mixed Outcomes: Using Promise.allSettled() for tasks that may partially fail.
  • Converting Callbacks: Wrapping callback-based functions in promises for compatibility with modern syntax.

By leveraging promises effectively, you can make asynchronous programming in JavaScript and React Native cleaner, more predictable, and more robust.

Top comments (0)