A Promise is an object that represents the eventual completion or failure of an asynchronous operation. It helps handle async tasks by allowing you to attach callbacks for success or failure.
Click to reveal answer
beginner
How do you create a new Promise?
You create a Promise by using the new Promise() constructor and passing a function with two parameters: resolve and reject. Inside this function, you perform your async task and call resolve() if it succeeds or reject() if it fails.
Click to reveal answer
beginner
What do the resolve and reject functions do in a Promise?
resolve is called when the async operation finishes successfully, passing the result. reject is called when the operation fails, passing an error or reason.
Click to reveal answer
beginner
Show a simple example of creating a Promise that resolves after 1 second.
Promises make async code easier to read and manage by avoiding "callback hell". They provide a clear way to handle success and errors, and can be chained for sequential async tasks.
Click to reveal answer
What are the two functions passed to the Promise constructor?
Athen and catch
Bstart and stop
Cresolve and reject
Dopen and close
✗ Incorrect
The Promise constructor receives a function with two parameters: resolve (for success) and reject (for failure).
Which method is used to handle a successful Promise result?
Acatch()
Bthen()
Cfinally()
Dstart()
✗ Incorrect
The then() method is used to handle the result when a Promise resolves successfully.
What does calling reject() inside a Promise do?
APauses the Promise
BMarks the Promise as fulfilled
CRestarts the Promise
DMarks the Promise as rejected
✗ Incorrect
Calling reject() marks the Promise as failed or rejected, triggering error handling.
How do you create a Promise that waits 2 seconds before resolving?