Welcome to Part 11 of the JavaScript for Beginners Series. In this part, we tackle one of the most important concepts for building modern web applications: Asynchronous JavaScript and Promises.
Synchronous vs. Asynchronous (الفرق بين المتزامن واللامتزامن)
Synchronous (Default Behavior)
By default, JavaScript is synchronous, meaning it runs one line of code at a time and must finish a task before moving to the next. If a task takes a long time (like fetching data from a server), it blocks the entire program.
Darija: جافاسكريبت فالأصل ديالو "متزامن" (synchronous)، يعني كينفذ الأوامر سطر بسطر، ومكيدوز للسطر الثاني حتى كيكمل الأول. إلا كانت شي عملية كتعطل (بحال تجيب معلومات من السيرفور)، البرنامج كامل كيتبلوكا.
Asynchronous
Asynchronous code allows long-running tasks to happen in the background without freezing the page. To handle this, we use Promises. A Promise is a special object that represents the eventual completion (or failure) of an asynchronous operation. It is a placeholder for a future value.
Darija: الكود "اللامتزامن" (Asynchronous) كيخلي هاد العمليات الطويلة تخدم فالخلفية بلا ما تبلوكي كلشي. الـ Promise هو بحال شي "وعد"، هو واحد الكائن (object) كيمثل النتيجة المستقبلية ديال ديك العملية، سواء نجحات أو فشلات.
Key Promise States
A Promise can be in one of three states:
- Pending (قيد الإنتظار): The initial state; the operation has not completed yet. Darija: العملية مزال مسالاتش.
- Fulfilled / Resolved (تم بنجاح): The operation completed successfully, and the Promise now has a resolved value. We handle this with .then(). Darija: العملية نجحات وعندها نتيجة. كنتعاملو معاها بـ .then().
- Rejected (فشل): The operation failed. We handle this with .catch(). Darija: العملية فشلت. كنتعاملو معاها بـ .catch().
Code Example
Here is how to create and consume a Promise that simulates fetching data:
// We create a new Promise that simulates fetching data
const fetchData = new Promise((resolve, reject) => {
const success = true; // Change to false to see the .catch() work
setTimeout(() => {
if (success) {
resolve("Data fetched successfully!"); // This is the success value
} else {
reject("Error: Could not fetch data."); // This is the error message
}
}, 2000); // Simulates a 2-second delay
});
console.log("Starting the fetch...");
// We use .then() and .catch() to handle the outcome
fetchData
.then((successMessage) => {
// This runs only if the promise is resolved
console.log(successMessage);
})
.catch((errorMessage) => {
// This runs only if the promise is rejected
console.error(errorMessage);
});
console.log("...code continues without blocking.");