Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 1 of 10 · Promises and Async/Await
Interview question

What is a Promise in JavaScript and what states can it have? JavaScript में Promise क्या है और इसकी क्या states होती हैं?

Answer

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It acts as a placeholder for a value that isn't available yet.

StateMeaning
PendingInitial state, operation not yet completed
FulfilledOperation completed successfully, has a resolved value
RejectedOperation failed, has a reason/error
// Creating a promise
const myPromise = new Promise((resolve, reject) => {
    const success = true;
    setTimeout(() => {
        if (success) {
            resolve('Operation succeeded');
        } else {
            reject('Operation failed');
        }
    }, 1000);
});

console.log(myPromise); // Promise { <pending> }

myPromise
    .then(result => console.log(result)) // 'Operation succeeded' after 1s
    .catch(error => console.log(error));

// A promise can only settle once - either fulfilled or rejected, never both
const p = new Promise((resolve, reject) => {
    resolve('first');
    reject('second'); // ignored, promise already settled
});
p.then(val => console.log(val)); // 'first'

// Once settled, state and value are locked in permanently
const settled = Promise.resolve(42);
settled.then(val => console.log(val)); // 42, every time it's used

Promise एक object है जो asynchronous operation के eventual completion या failure को represent करता है। यह ऐसे value के लिए placeholder है जो अभी available नहीं है।

Stateअर्थ
PendingInitial state, operation पूरा नहीं हुआ
FulfilledOperation successfully पूरा हुआ
RejectedOperation fail हुआ
const myPromise = new Promise((resolve, reject) => {
    const success = true;
    setTimeout(() => {
        if (success) resolve('Operation succeeded');
        else reject('Operation failed');
    }, 1000);
});

console.log(myPromise); // Promise { <pending> }

myPromise
    .then(result => console.log(result))
    .catch(error => console.log(error));

// Promise एक बार ही settle होता है
const p = new Promise((resolve, reject) => {
    resolve('first');
    reject('second'); // ignore हो जाता है
});
p.then(val => console.log(val)); // 'first'

Was this answer clear?