I have been running different code I wrote to observe the behavior of async ... await key words.
I have two examples, which behave drastically differently:
Example 1:
const func1 = async () => {
await setTimeout(() => console.log('first'), 0);
console.log('second')
console.log('third')
}
console.log('hi1');
func1();
console.log('hi2');
// logs hi1, hi2, second, third, first
Example2:
const func2 = async () => {
await console.log('first');
console.log('second');
console.log('third');
}
console.log('hi1');
func2();
console.log('hi2');
// logs hi1, second, third, hi2, first
I do understand everything in Example 1, but not Example 2. Specifically, I expect Example 2 to log
'hi1', 'first', 'second', 'third', 'hi2'
This is because there is nothing to wait for when logging 'first', so it should immediately log 'first', as Javascript is synchronous language.
So in summary I am curious of these two things:
Why does Example 2 log as is instead of logging
'hi1', 'first', 'second', 'third', 'hi2'.Can I use async ...await on non-asynchrnous code like
console.log('first')? Then shouldn't it return error? It does not, therefore I assume it is usable.
Any explanation would be appreciated!