So I was thinking that ok node is asynchronous (meaning multiple lines of code execute at the same time), then why we use the keyword async( which literally means asynchronous) to wait for a task to be done by keyword await (that is making it synchronous). Why there is not a keyword sync, because that's what we are doing? Can someone please explain the logic of keyword async? I am so confused.
The async
keyword enables the use of await
which is just a more streamlined syntax for writing code with promises and asynchronous operations. It does not make anything synchronous. It just allows you to use similar programming techniques as synchronous code, but it is all still asynchronous.
Can someone please explain the logic of keyword async? I am so confused.
When you use the async
keyword to declare a function, you are creating a different type of function that ALWAYS returns a promise. This is useful only for asynchronous programming - thus the async
keywords's affiliation with the term "asynchronous".
Further, the async
keyword does not make anything synchronous. It does allow you to use a more synchronous-like programming model which is a lot simpler to use, particularly for things like conditional branches in asynchronous control flow, but nothing that was asynchronous actually becomes synchronous.
As an example of how nothing becomes synchronous, run this example in the snippet and note the order of console.log()
statements. The async
function returns when it hits the first await
and the rest of the execution continues which the asynchronous operation is still going. This is a simulation with a timer, but that timer could be any other asynchronous operation such as an http request, a database operation, etc...
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
async function run() {
console.log("in run() 1");
await delay(100);
console.log("in run() 2");
}
console.log("before run()");
run();
console.log("after run()");
You can see from running this little example, that the run()
function has its execution suspends as soon as you hit the await
and it returns allowing the other code after the function call to run. Then, sometime later when the timer fires and the delay()
promise is resolved, the run()
function picks up where it was suspended and executes the rest of the function body.
This is operationally the same as this code using .then()
instead of async
and await
:
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
function run() {
console.log("in run() 1");
delay(100).then(() => {
console.log("in run() 2");
});
}
console.log("before run()");
run();
console.log("after run()");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With