JavaScript Promise, Async and Await
In JavaScript, Promise, async, and await are used to handle asynchronous operations.
For example, when we send data from JavaScript to a Laravel server, the server may take some time to respond. JavaScript can continue doing other work while waiting for the response.
Let's understand these concepts with a simple example.
1. What is a Promise?
A Promise is an object that represents the result of an asynchronous operation.
In simple words:
A Promise means: "I will give you the result later."
For example:
Here, the Promise takes 2 seconds to complete.
Initially, the Promise is:
After 2 seconds, it becomes:
because we called:
2. Promise States
A Promise has three main states:
Pending
The operation is still running.
Fulfilled
The operation was successful.
Rejected
The operation failed.
For example:
If success is true, the Promise is fulfilled.
If success is false, the Promise is rejected.
3. Using a Promise with .then()
We can get the result of a Promise using .then().
After 2 seconds, the output will be:
The .then() function runs when the Promise is successfully completed.
4. What is async?
The async keyword is used before a function.
An async function always returns a Promise.
For example:
When we call:
The result is a Promise.
To get the actual value, we can use .then():
Output:
5. What is await?
The await keyword is used to wait for a Promise to complete.
For example:
Now we can use await:
Here:
means:
Wait for the Promise returned by saveBlog() to complete.After 2 seconds:
6. Why do we need async and await?
Without async/await, we might use .then():
With async/await:
The second version is often easier to read.
7. Simple Real-Life Example
Imagine you are ordering food.
You place an order:
A Promise is like saying:
"I promise that I will give you the food when it is ready."
async means:
"This function can perform asynchronous work."
await means:
"Wait until the food is ready."
8. Complete Example
Let's combine Promise, async, and await.
Output:
After 2 seconds:
9. Promise + async + await Together
Remember this simple structure:
Here:
creates a Promise.
creates an asynchronous function.
waits for the Promise to complete.