𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗣𝗿𝗼𝗺𝗶𝘀𝗲𝘀 𝗔𝗻𝗱 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱
Think about ordering a pizza online.
You place your order. 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.
Operations like API requests, database calls, and timers take time. If JavaScript waited for each task to finish, your app would freeze. Instead, JavaScript runs other code while waiting for results.
What is a Promise?
A Promise is a placeholder for a value you will get in the future.
When you run: const promise = fetch("/users");
The data is not there yet. The Promise says: "I do not have the result now, but I will tell you when it is ready."
A Promise has three states:
- Pending
- Fulfilled (Success)
- Rejected (Failure)
Most modern APIs like fetch() return a Promise automatically. You do not need to create them manually every time. You just use them.
What does .then() do?
Many people think .then() retrieves data. It does not.
.then() registers a callback function. You are telling JavaScript: "When this Promise finishes, run this specific function."
It is like a food delivery app. You order food, and the app tells you: "Call me when the food arrives." The function waits for the signal.
Why use Async/Await?
You can chain .then() calls to get data step by step. This works, but long chains are hard to read.
Async/await makes your 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 function.
- Hit await and pause that function.
- Run the rest of the script.
- Once the task finishes, resume the function.
Summary:
- Promise = A future value.
- fetch() = Returns a Promise.
- .then() = Run this function when ready.
- await = Pause this function, not the whole program.
- async/await = A cleaner way to write Promises.
Source: https://dev.to/aarthirs/javascript-promises-asyncawait-explained-with-a-real-life-example-43bm