Skip to main content

What is Promise?

 In JavaScript, a Promise is a built-in object used to handle asynchronous operations. It represents a value that may be available now, or in the future, or never. Promises help manage asynchronous code in a more readable and maintainable way compared to callbacks.

Key Features of a Promise:

  1. States:

    • Pending: The initial state, neither fulfilled nor rejected.
    • Fulfilled: The operation was completed successfully.
    • Rejected: The operation failed.
  2. Methods:

    • .then(onFulfilled, onRejected): Attaches callbacks for when the promise is fulfilled or rejected.
    • .catch(onRejected): Attaches a callback for when the promise is rejected.
    • .finally(onFinally): Attaches a callback to be executed regardless of the promise's outcome.
  3. Creating a Promise: A promise is created using the Promise constructor, which takes a function with two parameters: resolve and reject.

Example 1: Basic Promise

javascript

const myPromise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("The operation was successful!"); } else { reject("The operation failed."); } }); myPromise .then(result => { console.log(result); // Logs: "The operation was successful!" }) .catch(error => { console.error(error); // Logs: "The operation failed." (if success is false) });

Example 2: Simulating an Asynchronous Operation

javascript

const fetchData = new Promise((resolve, reject) => { setTimeout(() => { const data = { id: 1, name: "John Doe" }; resolve(data); }, 2000); // Simulates a 2-second delay }); fetchData .then(data => { console.log("Data received:", data); }) .catch(error => { console.error("Error:", error); });

Example 3: Chaining Promises

javascript

const fetchData = () => { return new Promise((resolve, reject) => { 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" }) .catch(error => { console.error(error); });

Example 4: Using Promise.all

When you need to wait for multiple promises to resolve:

javascript

const promise1 = Promise.resolve("First"); const promise2 = Promise.resolve("Second"); const promise3 = Promise.resolve("Third"); Promise.all([promise1, promise2, promise3]) .then(results => { console.log(results); // Logs: ["First", "Second", "Third"] }) .catch(error => { console.error(error); });

Benefits of Promises:

  • Avoids callback hell (nested callbacks).
  • Improves readability and maintainability.
  • Works well with modern async/await syntax for even cleaner asynchronous code.

Would you like to learn about async/await, or do you have a specific use case in mind?

Comments

Popular posts from this blog

What is Arrow Function?

 An arrow function is a concise way to write functions in JavaScript, introduced in ES6 (ECMAScript 2015). It uses the => syntax and is often preferred for its simplicity and ability to maintain the this context of the surrounding code. Syntax (param1, param2, ..., paramN) => expression If the function body contains multiple statements, you need to wrap it in curly braces {} and use the return keyword explicitly: (param1, param2, ..., paramN) => { // multiple statements return result; } If there is only one parameter, you can omit the parentheses: param => expression If there are no parameters, you must use empty parentheses: () => expression Examples Single-line arrow function: const add = ( a, b ) => a + b; console . log ( add ( 2 , 3 )); // Output: 5 Multi-line arrow function: const multiply = ( a, b ) => { const result = a * b; return result; }; console . log ( multiply ( 2 , 3 )); // Output: 6 Arrow function with one paramete...

What is event in react js?

 In React.js, an event is an object that represents an action or occurrence, such as a user interaction (e.g., a mouse click, a key press, or a form submission). React handles events in a declarative and efficient way, providing a synthetic event system that is consistent across different browsers. Key Features of Events in React: Synthetic Events : React wraps native browser events in its own event system called SyntheticEvent . This ensures compatibility across browsers and provides additional features like event pooling for performance optimization. Event Handling : Events in React are written as camelCase (e.g., onClick , onChange ), unlike plain HTML where events are written in lowercase (e.g., onclick , onchange ). Event handlers are passed as functions, typically as references or inline arrow functions. Binding this : When using class components, you may need to bind the event handler to the component instance ( this ). In function components, this is not required, especial...

React Interview Questions and Answers

 React is an efficient, flexible, and open-source JavaScript library designed to help developers create simple, fast, and scalable web applications. It was created by Jordan Walke, a software engineer at Facebook, and was first deployed on Facebook’s News Feed in 2011 and Instagram in 2012. React's simplicity and effectiveness make it accessible for developers with a JavaScript background to quickly build powerful web applications. Today, React is widely used by leading tech companies, including Facebook, Dropbox, Instagram, WhatsApp, Atlassian, and Meta. Its popularity stems from powerful features like the Virtual DOM, Components, State and Props, JSX, Hooks, and Routing, which simplify and enhance web development. To secure developer roles at top companies using React, it's essential to master the framework and prepare thoroughly. Familiarizing yourself with these top React interview questions can help you stand out as an expert in front of interviewers. 1. What is React.js? ...