0
If I understand correctly, a function declared with the keyword async must return a promise. In the case of the function async3() we have 1 billion iterations, which makes the return value take a little longer. What I was hoping would happen is that by invoking the function sync1() and sync2() immediately show me the log in the console and, later, the log of the function async3(). However, what I see is that the function sync1() and sync2() only show after the async3() have finished. The function would not be supposed async3() running in another thread or outside the Event loop without blocking the execution of the other functions?
Can someone clarify why this behavior?
function sync1() {
console.log(1);
}
function sync2() {
console.log(2);
}
async function async3() {
let iteration = 0;
let number = 0;
while (iteration <= 1000000000) {
number = iteration;
iteration++;
}
return number;
}
sync1();
sync2();
async3().then((val) => console.log(val));
The function sync1() and the sync2() only show on the console after the async3() have completed all iterations. I’m confused.
This answers your question? How ES7 async/await works?
– Augusto Vasques
@Augustovasques Hello Augusto. Thank you for the suggestion. It’s a good answer, which discusses the various types of syntax in which we can use the predecessors, but here, in this particular case, I wanted to understand why I have synchronous behavior in asynchronous logic.
– joaogeraldes
Reading suggestion: How asynchronous programming works in Javascript?
– Augusto Vasques