Home > Web Front-end > JS Tutorial > Promises in JavaScript and React Native: Creation, Usage, and Common Scenarios

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

Barbara Streisand
Release: 2024-11-13 00:37:02
Original
207 people have browsed it

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
  });
}
Copy after login
Copy after login

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
Copy after login
Copy after login

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");
Copy after login
Copy after login

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 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
  });
}
Copy after login
Copy after login

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.

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
Copy after login
Copy after login

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.

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");
Copy after login
Copy after login

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.

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));
Copy after login

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

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));
Copy after login

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.

The above is the detailed content of Promises in JavaScript and React Native: Creation, Usage, and Common Scenarios. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template