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

Nov 13, 2024 am 12:37 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles