11: استخدام ال promises في الجافاسكريبت

3 min read 7 months ago
Published on Aug 20, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will explore the use of Promises in JavaScript. Promises are a fundamental concept for handling asynchronous operations, allowing you to work with tasks that may take time to complete without blocking your code execution. Understanding Promises is essential for writing modern JavaScript applications, especially when dealing with APIs or any asynchronous tasks.

Step 1: Understanding the Promise Object

  • A Promise represents a value that may be available now, or in the future, or never.
  • It can be in one of three states:
    • Pending: Initial state, neither fulfilled nor rejected.
    • Fulfilled: The operation completed successfully.
    • Rejected: The operation failed.

Practical Tip

Use Promises to manage operations that require waiting, such as fetching data from a server.

Step 2: Creating a Promise

To create a Promise, use the Promise constructor, which takes a function with two parameters: resolve and reject.

const myPromise = new Promise((resolve, reject) => {
    // Asynchronous operation
    const success = true; // Simulate success or failure
    if (success) {
        resolve("Operation was successful!");
    } else {
        reject("Operation failed.");
    }
});

Step 3: Using Promises

To work with a Promise, use the .then() method for fulfilled promises and .catch() for rejected promises.

Example

myPromise
    .then(result => {
        console.log(result); // This runs if the promise is fulfilled
    })
    .catch(error => {
        console.log(error); // This runs if the promise is rejected
    });

Step 4: Chaining Promises

Promises can be chained to perform a series of asynchronous tasks. Each .then() returns a new Promise.

Example

myPromise
    .then(result => {
        console.log(result);
        return new Promise((resolve) => resolve("Next operation successful!"));
    })
    .then(nextResult => {
        console.log(nextResult);
    })
    .catch(error => {
        console.log(error);
    });

Common Pitfall

Avoid nesting Promises inside each other. Instead, chain them for better readability and error handling.

Step 5: Promise.all for Concurrent Execution

Use Promise.all() to execute multiple Promises concurrently and wait for all of them to complete.

Example

const promise1 = Promise.resolve("First promise");
const promise2 = Promise.resolve("Second promise");

Promise.all([promise1, promise2])
    .then(results => {
        console.log(results); // ["First promise", "Second promise"]
    })
    .catch(error => {
        console.log(error);
    });

Conclusion

In this tutorial, we covered the basics of using Promises in JavaScript, including how to create, use, and chain them effectively. Promises are a powerful tool for managing asynchronous operations and can greatly enhance your JavaScript code's readability and maintainability.

Next Steps

  • Practice creating and chaining Promises with different asynchronous operations.
  • Explore async/await syntax as a more modern approach to working with Promises.