Skip to main content

Introduction to promises (promise)

What is a Promise?​

Think of a promise as an order you place at a restaurant. You place the order (request) and wait for your dish to be ready (response). In JavaScript, a promise is an object that represents the completion or failure of an asynchronous operation.

Why the Promises?​

They allow you to manage operations that take time (such as loading data from the internet) without blocking the rest of the code. They help avoid complicated and hard-to-follow code structures, known as "callback hell." Structure of a Promise Creating a Promise

let maPromesse = new Promise((resolve, reject) => {
// Code qui fait quelque chose, puis appelle resolve() si tout va bien,
// ou reject() en cas d'erreur.
});

Managing Promise Responses​

Processing a Success => Use .then()​

maPromesse.then((resultat) => {
console.log(resultat); // Gérer la réussite
});

Handling an Error => Use .catch()​

maPromesse.catch((erreur) => {
console.error(erreur); // Gérer l'erreur
});

Examples and Common Uses​

Network Promises and Requests with Fetch API​

The Fetch API uses promises to handle network request responses.

fetch('https://exemple.com/donnees')
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(donnees => console.log(donnees))
.catch(erreur => console.error('Erreur :', erreur));

fetch rejects on a network failure. An HTTP 404 or 500 is still a fulfilled response, so check response.ok. For a cancellable request, create an AbortController and pass its signal.

Chain of Promises​

You can chain multiple asynchronous operations that must execute one after the other. Each .then() can return a new promise, thus forming a chain.

Advanced Promise Methods​

  • Promise.all() => Used to wait until multiple promises are all resolved. Example: Run multiple queries in parallel.

  • Promise.race() => Resolves or rejects as soon as the first promise in the set is resolved or rejected.

  • Promise.allSettled() => Waits for all promises to be either resolved or rejected, and returns their result.

  • Promise.any() => Resolves as soon as one of the promises is resolved. Ignores rejections unless all promises are rejected.