JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What are promises in JavaScript and how do you use them?

Asked on Jul 11, 2024

Answer

Promises in JavaScript are objects that represent the eventual completion or failure of an asynchronous operation. They provide a cleaner and more manageable way to handle asynchronous code compared to callbacks.
<!-- BEGIN COPY / PASTE -->
        const myPromise = new Promise((resolve, reject) => {
            const success = true; // Simulate success or failure
            if (success) {
                resolve("Operation was successful!");
            } else {
                reject("Operation failed.");
            }
        });

        myPromise
            .then(result => {
                console.log(result); // "Operation was successful!"
            })
            .catch(error => {
                console.error(error); // "Operation failed."
            });
        <!-- END COPY / PASTE -->
Additional Comment:
  • Promises have three states: "pending", "fulfilled", and "rejected".
  • Use "then" to handle the resolved value and "catch" for errors.
  • Promises help avoid "callback hell" by allowing chaining of asynchronous operations.
✅ Answered with JavaScript best practices.
← Back to All Questions