What is a Promise in JavaScript?
A
A data type B
An event listener C
An object representing a future completion or failure of an async task D
A reserved word
Analysis & Theory
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation.
Which of these is NOT a state of a Promise?
A
fulfilled B
rejected C
pending D
resolved
Analysis & Theory
The actual states are: `pending`, `fulfilled`, and `rejected`. `resolved` is not a formal state.
How do you handle a resolved Promise?
A
.done() B
.resolve() C
.then() D
.catch()
Analysis & Theory
Use `.then()` to handle the result when a Promise is fulfilled.
What does `.catch()` do?
A
Catches any value from a `.then()` call B
Handles rejected Promises (errors) C
Executes immediately D
Stops Promise execution
Analysis & Theory
`.catch()` is used to handle errors (rejected Promises).
What will this code print?
```js
Promise.resolve(5).then(x => console.log(x));
```
A
undefined B
Promise C
5 D
Error
Analysis & Theory
The Promise is resolved with value 5, so `console.log(5)` is executed.
Which is the correct way to create a custom Promise?
A
`new Promise()` B
`Promise.create()` C
`Promise(function)` D
`promise()`
Analysis & Theory
A Promise is created using the constructor `new Promise((resolve, reject) => { ... })`.
Which function is called if the Promise is rejected?
A
resolve() B
then() C
catch() D
finally()
Analysis & Theory
`catch()` is used to handle Promise rejections.
What will this log?
```js
let p = new Promise((resolve, reject) => {
reject('Failed');
});
p.catch(err => console.log(err));
```
A
undefined B
Error C
Failed D
Promise
Analysis & Theory
The Promise is rejected with 'Failed', so that value is printed.
Which method runs no matter if the Promise is resolved or rejected?
A
.then() B
.catch() C
.done() D
.finally()
Analysis & Theory
`.finally()` runs whether the Promise was fulfilled or rejected.
What will this output?
```js
Promise.reject('Error')
.then(() => console.log('Then'))
.catch(err => console.log(err));
```
A
Then B
undefined C
Error D
Promise
Analysis & Theory
The Promise is rejected, so the `.catch()` block logs `'Error'`.