JavaScript
/Intermediate
Promises
Definition
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It is a proxy for a value not necessarily known when the promise is created.
Explain Like I'm New
Imagine ordering food at a restaurant. They give you a buzzer (the Promise). You can't eat the buzzer, but it promises that eventually it will ring (Resolve) and you'll get food, or it will flash red (Reject) if they ran out of ingredients. While waiting, you can chat with your friends (run other code).
Real World Example
Fetching data from a database or a remote API. You don't want to freeze the entire website while waiting for the data to download over the internet.
Common Use Cases
- •Fetching data from an API (fetch)
- •Reading files from a hard drive
- •Any operation that takes an unpredictable amount of time
Interactive Example
Loading...
Console output will appear here...
Interview Questions
basic
- What is a Promise?
- What are the three states of a Promise?
intermediate
- How do you handle errors in a Promise chain?
- What is Promise.all() and when would you use it?
advanced
- What is the difference between Promise.all() and Promise.race()?
- How can you create a Promise that automatically resolves after 2 seconds?
trick
- If you return a value inside a .then() block, what happens?