10: ال promises في الجافاسكريبت | promises in javascript
Table of Contents
Introduction
This tutorial will guide you through understanding promises in JavaScript, a crucial concept for managing asynchronous operations. Promises help streamline code execution and improve readability by allowing you to handle tasks that take time, such as API calls or file reading, without blocking the main thread.
Step 1: Understanding Promises
A promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Here are the key states of a promise:
- Pending: The initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
Practical Advice
- Use promises to manage tasks that may not complete immediately, such as fetching data from a server.
Step 2: Creating a Promise
You can create a promise using the Promise
constructor. Here's how:
const myPromise = new Promise((resolve, reject) => {
// Simulate an asynchronous operation
const success = true; // Change to false to test rejection
setTimeout(() => {
if (success) {
resolve("Operation succeeded");
} else {
reject("Operation failed");
}
}, 1000);
});
Practical Advice
- Always handle both success and failure when creating promises to avoid unhandled promise rejections.
Step 3: Consuming a Promise
To handle the result of a promise, use the then()
and catch()
methods:
myPromise
.then(result => {
console.log(result); // Logs "Operation succeeded"
})
.catch(error => {
console.error(error); // Logs "Operation failed" if rejected
});
Practical Advice
- Use
then()
for handling fulfilled promises andcatch()
for handling rejected promises.
Step 4: Chaining Promises
You can chain multiple promises to perform sequential asynchronous operations:
const fetchData = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched");
}, 1000);
});
};
fetchData()
.then(data => {
console.log(data); // Logs "Data fetched"
return "Processing data";
})
.then(processedData => {
console.log(processedData); // Logs "Processing data"
});
Practical Advice
- Chaining allows you to maintain a clean flow of asynchronous code without deeply nested callbacks.
Step 5: Using Async/Await with Promises
The async
and await
keywords simplify promise consumption by allowing you to write asynchronous code that looks synchronous:
const asyncFunction = async () => {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
};
asyncFunction();
Practical Advice
- Use
async/await
for better readability, especially when dealing with multiple asynchronous operations.
Conclusion
Promises are a powerful feature in JavaScript that enhance the way you handle asynchronous operations. By understanding their states, how to create and consume them, and utilizing async/await
, you can write cleaner and more efficient code.
Next Steps
- Experiment with promises in your own projects.
- Explore additional features like
Promise.all()
for handling multiple promises concurrently.