𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗣𝗿𝗼𝗺𝗶𝘀𝗲𝘀 𝗮𝗻𝗱 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱
Imagine you order a pizza online.
You do not stand at your door doing nothing until it arrives. You watch videos, work, or talk to friends. When the pizza arrives, you eat.
JavaScript works the same way.
Tasks like API requests or database calls take time. If JavaScript waited for each task, your app would freeze. Instead, it continues running other code while waiting.
A Promise represents a value that arrives in the future.
A Promise has three states:
- Pending
- Fulfilled (Success)
- Rejected (Failure)
You rarely see the code used to create a new Promise. This is because modern tools like fetch() already return a Promise for you.
What does .then() do?
Many people think .then() retrieves data. It does not.
.then() registers a callback function. You tell JavaScript: "When this Promise finishes, run this function."
It is like a delivery app. You order food, and the app says: "Call me when the food arrives." The function waits for the result.
Why use Async/Await?
You can chain .then() calls to get user data, then posts, then comments. This works, but long chains are hard to read.
Async/await makes code look like normal, step-by-step code. It is cleaner and easier to follow.
Does await block JavaScript?
This is a common interview question. The answer is no.
When JavaScript hits an await keyword, it pauses only that specific async function. The rest of your application keeps running.
Example flow:
- Run code in the async function.
- Hit await and pause that function.
- Run the rest of the application.
- When the task finishes, resume the async function.
Async/await is just a cleaner way to write Promises. It is syntactic sugar.
Key takeaways:
- Promise = A future value.
- fetch() = Returns a Promise.
- .then() = Run this when ready.
- await = Pause this function, not the whole program.
- async/await = Cleaner Promise syntax.
Source: https://dev.to/aarthirs/javascript-promises-asyncawait-explained-with-a-real-life-example-43bm