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.
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:
To create a promise, we use the Promise constructor, which takes a single function (the executor function) with two parameters:
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 }); }
In this example:
Once a promise is created, we can handle its outcome using:
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
In this example:
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");
Use Case: Fetching data from REST APIs or other network requests, where we need to handle both successful responses and errors.
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 }); }
Use Case: Useful for logging in a user and then fetching profile data based on their identity.
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
Use Case: Fetching multiple resources concurrently, such as fetching posts and comments from separate API endpoints.
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");
Use Case: Setting a timeout for network requests, so they don’t hang indefinitely if the server is slow or unresponsive.
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));
Use Case: Useful when executing multiple requests where some may fail, such as fetching optional data sources or making multiple API calls.
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.
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));
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.
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:
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!