JavaScript Interview Questions

23 Questions
JavaScript

JavaScript

Web DevelopmentFrontendBackend

Question 8

What are promises in JavaScript?

Answer:

Promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a more elegant way to handle asynchronous operations compared to traditional callback functions, avoiding callback hell and improving error handling. They have three states: pending, fulfilled, and rejected.

Here is an example demonstrating the use of promises:

let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Promise resolved!');
    }, 1000);
});

promise.then((message) => {
    console.log(message); // 'Promise resolved!'
}).catch((error) => {
    console.error(error);
});

In this example, a promise is created that resolves after 1 second. The then method is used to handle the resolved value, and the catch method is used to handle any errors.

Recent job openings