العودة إلى الدورة

Introduction to Promises (The Structure)

JavaScript: الدورة الكاملة للمبتدئين من 'الصفر إلى الاحتراف'

96. Introduction to Promises

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation, and its resulting value. Promises solve 'callback hell' by providing a cleaner, sequential flow.

Promise States

A Promise is always in one of three mutually exclusive states:

  1. Pending: The initial state; the operation has not finished yet.
  2. Fulfilled (Resolved): The operation completed successfully, and the Promise now has a resulting value.
  3. Rejected: The operation failed, and the Promise now has a reason for the failure (an error).

Creating a Simple Promise

javascript const myPromise = new Promise((resolve, reject) => { // Simulate a successful operation after 1 second setTimeout(() => { const randomNumber = Math.random(); if (randomNumber > 0.5) { resolve('Data successfully fetched!'); // Success path } else { reject(new Error('Network connection failed.')); // Failure path } }, 1000); });

In the next lesson, we learn how to consume this promise.