Tuesday, January 4, 2022

Async and await

First, problem without async/await:-

Imagine:

  1. Get user from server
  2. Get orders using user id
  3. 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

Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly. Main keywords: export → make something available...