Promise Basics
Promises/Async/Await: Promise Basics
What is a Promise in JavaScript?
View Answer:
let promise = new Promise(function(resolve, reject) {
// a mock async action using setTimeout
setTimeout(function() {
resolve('Hello world!'); // The async operation was successful
}, 1000);
});
promise.then(function(successMessage) {
// successMessage is whatever we passed in the resolve(...) function above.
console.log(successMessage);
}, function(errorMessage) {
// errorMessage is whatever we passed in the reject(...) function above.
console.log(errorMessage);
});
What are the three states of a Promise?
View Answer:
Pending: The Promise's outcome hasn't yet been determined, because the asynchronous operation that will produce its result hasn't completed yet.
Fulfilled: The asynchronous operation completed successfully, and the Promise's resulting value is now available.
Rejected: The asynchronous operation failed, and the Promise will never be fulfilled. In the rejected state, a Promise has a reason that indicates why the operation failed.
It's important to note that a Promise is only pending before it is either fulfilled or rejected. Once a Promise has been fulfilled or rejected, it becomes settled and its state can't change. The Promise's value or reason, once set, can't change either.
What is the purpose of the resolve and reject functions within a Promise?
View Answer:
Here's an example of using resolve:
let promise = new Promise(function(resolve, reject) {
setTimeout(() => resolve("Operation successful"), 1000);
});
promise.then(value => console.log(value)); // logs "Operation successful" after 1 second
Here's an example of using reject:
let promise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error("Operation failed")), 1000);
});
promise.catch(error => console.log(error)); // logs "Error: Operation failed" after 1 second
Can you explain the function of the Promise object in JavaScript?
View Answer:
let promise = new Promise(function (resolve, reject) {
// executor or producer
});
What is the function called that we pass to the newly created promise?
View Answer:
let promise = new Promise(function (resolve, reject) {
// executor or producer
});
Could you list the internal properties of a Promise object created by the Promise constructor?
View Answer:
// Example: RESOLVE
let promise = new Promise(function (resolve, reject) {
// the function is executed automatically when the promise is constructed
// after 1 second signal that the job is done with the result "done"
setTimeout(() => resolve('done'), 1000);
});
// Example: REJECT
let promise = new Promise(function (resolve, reject) {
// after 1 second signal that the job is finished with an error
setTimeout(() => reject(new Error('Whoops!')), 1000);
});
What is a promise that is either resolved or rejected called?
View Answer:
What is the main limitation of a Promise in JavaScript?
View Answer:
let promise = new Promise(function (resolve, reject) {
resolve('done');
reject(new Error('…')); // ignored
setTimeout(() => resolve('…')); // ignored
});
What are the three subscribing (consumers) methods used in Promises?
View Answer:
Can you explain the function of the promise.then() method?
View Answer:
Syntax: promise.then(onFulfilled[, onRejected]);
let promise = new Promise(function (resolve, reject) {
setTimeout(() => resolve('done!'), 1000);
});
// resolve runs the first function in .then
promise.then(
(result) => console.log(result), // shows "done!" after 1 second
(error) => console.log(error) // doesn't run
);
///////////////////////////////////
let promise2 = new Promise(function (resolve, reject) {
babab;
});
// error runs the first function in .then
promise2.then(
(result) => console.log(result), // doesn't run
(error) => console.log(error.name) // returns ReferenceError
);
If we are interested only in errors, we can use null as the first argument ( .then(null, errorHandlingFunction); ). The then method/function returns a Promise which allows for method chaining.
Can you explain the function of the promise catch() method?
View Answer:
Syntax: promise.catch(onRejected);
let promise = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Whoops!')), 1000);
});
// .catch(f) is the same as promise.then(null, f)
promise.catch(console.log); // shows "Error: Whoops!" after 1 second
Can you explain the function of the promise finally() method?
View Answer:
Syntax: promise.finally(onFinally);
new Promise((resolve, reject) => {
setTimeout(() => resolve('result'), 2000);
})
.finally(() => console.log('Promise ready'))
.then((result) => console.log(result)); // <-- .then handles the result
We use it to perform cleanup tasks once the promise settles, as it always executes irrespective of whether the promise is fulfilled or rejected.
In JavaScript, what are the advantages of promises versus callbacks?
View Answer:
Syntax: promise.finally(onFinally);
new Promise((resolve, reject) => {
setTimeout(() => resolve('result'), 2000);
})
.finally(() => console.log('Promise ready'))
.then((result) => console.log(result)); // <-- .then handles the result
What is the difference between .then() and .catch()?
View Answer:
How can you chain multiple Promises together?
View Answer:
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000);
});
promise
.then(result => {
console.log(result); // 1
return result * 2;
})
.then(result => {
console.log(result); // 2
return result * 2;
})
.then(result => {
console.log(result); // 4
return result * 2;
});
What is Promise.all() and when would you use it?
View Answer:
const promises = [
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 1');
}, 1000);
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 2');
}, 2000);
}),
];
const allPromises = Promise.all(promises);
allPromises.then((values) => {
console.log(values); // ['Promise 1', 'Promise 2']
});
Can you explain the use of Promise.race() in JavaScript?
View Answer:
Promise.race([promise1, promise2, promise3]).then(function(value) {
// do something with the value of the first promise that resolves
});
What is the purpose of Promise.resolve() and Promise.reject()?
View Answer:
How do you conditionally handle promise reject or resolve?
View Answer:
let promise = new Promise((resolve, reject) => {
let value = /* some async operation */;
if (value) resolve(value);
else reject('error');
});
promise.then(result => {
if (result > 10) console.log('High');
else console.log('Low');
}).catch(error => {
if (error === 'error') console.log('Failed');
});