First, problem without async/await:-
Imagine:
- Get user from server
- Get orders using user id
- Get payment using order id
Using Promise chaining:
getUser()
.then(user => {
return getOrders(user.id);
})
.then(orders => {
return getPayment(orders[0].id);
})
.then(payment => {
console.log(payment);
});
Works fine, but lots of .then().
Same thing:
async function getData() {
const user = await getUser();
const orders = await getOrders(user.id);
const payment = await getPayment(orders[0].id);
console.log(payment);
}
Looks like normal code.
What does async do?
async = This function will return a Promise.
async function hello() {
return "Hi";
}is equivalent to function hello() {
return Promise.resolve("Hi");
}
What does await do?
“Wait here until Promise finishes, then give me the result.”
One important rule:
await only works inside an async function.
❌ Wrong:
const data = await getUser();
✅ Correct:
async function test() {
const data = await getUser();
}Promise = "I will give result later"
async = "This function returns a promise"
await = "Wait until promise finishes"
No comments:
Post a Comment