The promise is used to handle async operation and its resulting value will be success or failure.
A Promise has basically three state
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation completed successfully.
it uses the resolve method for this
rejected: meaning that the operation failed.
it is use reject method for this.
function checkPostiveNumber (number) {
return new Promise((resolve, reject) => {
try {
if((number<0))
{
throw new Error(` ${number} is not a postive number` );
}
} catch(msg) {
reject(`Error in callback ${msg}`);
}
resolve(`${number} is a positive number`)
});
}
let data=checkPostiveNumber(1);
console.log(data);
Promise {: "1 is a postive number"}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "1 is a postive number"
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "1 is a postive number"
C# Dictionary – Interview Questions
Q 1: What is a Promise?
Ans: A Promise represents the eventual result of an asynchronous operation.
Q 2: What are Promise states?
Ans: Pending, Fulfilled, and Rejected.
Q 3: Why use Promises?
Ans: To handle async operations more cleanly than callbacks.
Q 4: What is then() used for?
Ans: To handle successful Promise resolution.
Q 5: What is catch() used for?
Ans: To handle Promise errors.