JavaScript promises: resolve, reject, then and catch explained

JavaScript promises: resolve, reject, then and catch explained
  • maPromesse is the variable holding the Promise object.
  • resolve and reject are functions supplied by the Promise constructor.
  • The code inside the function defines what the promise does.
  • If the action succeeds, you call resolve with a success message (optional).
  • If the action fails, you call reject with an error message (optional).

Working with a promise

The .then() and .catch() methods handle the outcome of a promise:

code
maPromesse
 .then((message) => {
    console.log("Succès:", message);
  })
  .catch((erreur) => {
    console.log("Erreur:", erreur);
  });
    • .then() runs if the promise is resolved. The success message is passed to it as an argument.
    • .catch() runs if the promise is rejected. The error message is passed to it as an argument.

    When to use them

    Promises are useful for asynchronous operations, such as downloading an image from a server. Instead of blocking the code while the download finishes, the promise lets other work carry on and handles the result of the download once it is available.

    Replacing callbacks

    Promises are a more readable alternative to nested callbacks. Here is a function written with callbacks, converted into a function that uses a promise:

    javascript
    function watchTutorialCallback(successCallback, errorCallback, erreur = false) {
      // ... function body ...
      if (erreur) {
        errorCallback("Message d'erreur");
      } else {
        successCallback("Message de succès");
      }
    }
    javascript
    function watchTutorialPromise(erreur = false) {
      return new Promise((resolve, reject) => {
        // ... function body ...
        if (erreur) {
          reject("Message d'erreur");
        } else {
          resolve("Message de succès");
        }
      });
    }

    Using .then() and .catch() makes the code clearer and keeps you out of “callback hell”.

    Advanced methods

    • Promise.all(): runs several promises in parallel and returns an array of the results once every promise has resolved.
    • Promise.race(): runs several promises in parallel and returns the result of the first promise to resolve or reject.

    Conclusion

    Promises are a powerful tool for handling asynchronous operations in JavaScript. They let you write more readable code and avoid the problems that come with nested callbacks. Do go through the examples from the video and practise until this essential concept sticks.

    Promises in JavaScript can look complicated at first, but they are simpler than they seem. This tutorial, based on the video “JavaScript Promises In 10 Minutes” by Web Dev Simplified, walks you through the key concepts and the syntax of promises.

    The basic idea

    A promise in JavaScript works like a promise in real life. You commit to doing something, and that promise has two possible outcomes:

    • Resolved: the promise was kept.
    • Rejected: the promise could not be kept.
    •  

    Syntax

    To create a promise, you use the Promise constructor:

    javascript
    const succes = true; // replace with your own condition
    
    let maPromesse = new Promise((resolve, reject) => {
      // Code that fulfils the promise
      if (succes) {
        resolve("Message de succès");
      } else {
        reject("Message d'échec");
      }
    });

    In this example:

      • maPromesse is the variable holding the Promise object.
      • resolve and reject are functions supplied by the Promise constructor.
      • The code inside the function defines what the promise does.
      • If the action succeeds, you call resolve with a success message (optional).
      • If the action fails, you call reject with an error message (optional).

      Working with a promise

      The .then() and .catch() methods handle the outcome of a promise:

      code
      maPromesse
       .then((message) => {
          console.log("Succès:", message);
        })
        .catch((erreur) => {
          console.log("Erreur:", erreur);
        });
        • .then() runs if the promise is resolved. The success message is passed to it as an argument.
        • .catch() runs if the promise is rejected. The error message is passed to it as an argument.

        When to use them

        Promises are useful for asynchronous operations, such as downloading an image from a server. Instead of blocking the code while the download finishes, the promise lets other work carry on and handles the result of the download once it is available.

        Replacing callbacks

        Promises are a more readable alternative to nested callbacks. Here is a function written with callbacks, converted into a function that uses a promise:

        javascript
        function watchTutorialCallback(successCallback, errorCallback, erreur = false) {
          // ... function body ...
          if (erreur) {
            errorCallback("Message d'erreur");
          } else {
            successCallback("Message de succès");
          }
        }
        javascript
        function watchTutorialPromise(erreur = false) {
          return new Promise((resolve, reject) => {
            // ... function body ...
            if (erreur) {
              reject("Message d'erreur");
            } else {
              resolve("Message de succès");
            }
          });
        }

        Using .then() and .catch() makes the code clearer and keeps you out of “callback hell”.

        Advanced methods

        • Promise.all(): runs several promises in parallel and returns an array of the results once every promise has resolved.
        • Promise.race(): runs several promises in parallel and returns the result of the first promise to resolve or reject.

        Conclusion

        Promises are a powerful tool for handling asynchronous operations in JavaScript. They let you write more readable code and avoid the problems that come with nested callbacks. Do go through the examples from the video and practise until this essential concept sticks.

        Damien Flandrin Web developer since 2010, creator of Gekkode and Email Impact. Every article is tested on a real project before publication. Contact
        Newsletter

        New tests, tutorials and projects, by e-mail.

        Reproducible tests, versioned code, dated results. Never any spam.