Understanding Promises and Async / Await in JavaScript (ES6+)
Learn to write clean, maintainable asynchronous JavaScript without callback hell using Promises and async/await syntax.
Concepts & Theory
A `Promise` represents a future value that is currently pending, fulfilled, or rejected with an error.
The `async` keyword ensures a function returns a promise. Inside an async function, `await` pauses execution until the promise settles.
Use `Promise.all([p1, p2])` to execute concurrent tasks simultaneously instead of waiting sequentially.
Code Example
Run in Playground// 1. Définition d'une fonction asynchrone
async function chargerDonneesUtilisateur(userId) {
try {
const reponse = await fetch(`https://api.example.com/users/${userId}`);
if (!reponse.ok) {
throw new Error(`Erreur HTTP: ${reponse.status}`);
}
const utilisateur = await reponse.json();
return utilisateur;
} catch (erreur) {
console.error("Échec du chargement :", erreur.message);
throw erreur;
}
}
// 2. Parallélisation avec Promise.all
async function chargerDashboard() {
const [profil, stats] = await Promise.all([
fetch('/api/profil').then(r => r.json()),
fetch('/api/stats').then(r => r.json()),
]);
console.log("Données chargées en parallèle :", profil, stats);
}Common Pitfalls & Mistakes
✗ Awaiting independent promises sequentially
const user = await fetchUser();
const posts = await fetchPosts();const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);Awaiting independent tasks in series causes unnecessary round-trips. Promise.all runs them concurrently.
Frequently Asked Questions
What is the difference between .then() and async/await?▾
`async/await` is syntactic sugar built on top of Promises. It allows writing asynchronous logic with the clarity of synchronous control flow.
Master JavaScript with interactive exercises
Complete hands-on code challenges in your browser with real-time feedback and progressive hints.
