Possible duplicate of await is only valid in async function.
I am new to NodeJS
and I found the concept of async-await
a bit confusing.
After some reading and muddling around, this is my understanding of the same.
Suppose, I have a function sum
like this.
function sum(a, b) {
// print the numbers
for (var i = 0; i < 100000; i++) {
console.log(i);
}
// settimeout
new Promise (resolve => {
setTimeout(resolve, 1000);
});
return a+b;
}
function main() {
let a = sum(5,2);
console.log(a);
}
main();
It allocates a new thread for the timer and continues with the normal flow. It prints all the numbers first, returns a 7
and then waits for 1 second before exiting.
But now I want to execute the lines in the order they are written. It makes sense to put an await
keyword before the timer Promise
.
async function sum(a, b) {
// print the numbers
for (var i = 0; i < 100000; i++) {
console.log(i);
}
// settimeout
await new Promise (resolve => {
setTimeout(resolve, 1000);
});
return a+b;
}
Issue 1: Here, I don't understand the obligation to put async
to use await
. Only putting async
just makes the function return a Promise
instead of a value. the flow is unchanged. It still prints all the number before printing 7
.
Issue 2: I think the word async
before a function misleads into thinking that the function calls would be asynchronous, though they are not. Any clarification with respect to design?
Issue 3:
- In
NodeJS
, there is no concept of synchronous or asynchronous function call unless we have some blocking function like timer, remote requests and IO operations. That's where the concept ofasync-await
comes into picture. Otherwise, it's just a single thread even if the program hasPromises
. - Putting
async
besides a function just makes it return aPromise
instead of a value. It does not alter the program flow. Perhaps, it just puts some additional machinery to handleawait
(if any) just a guess!!. async
does not necessarily make any function (or its call) asynchronous. Call to function havingasync
keyword will still be synchronous unless it contains anotherPromise
that keeps it waiting. That's whereawait
comes in.
Is my whole understading correct?