Wednesday 11 September 2019

javascript - code inside async function executes before the code that follows it

Late answer here, and Quentin is exactly right, but it's helpful sometimes to diagram these things. Let's look at really simple async function:



async function foo() {
console.log("a");
await something();
console.log("b");
return 42;
}



That function has two parts:




  • A synchronous part: Everything up to (but not including) the first await or return (or if it just ends). So in the above, that's the console.log("a"); and the call to something (but not the bit waiting for its result).

  • An asynchronous part: Anything following that first await.



If we were to rewrite that function with explicit promises, it would look something like this (hand-waving away details):




function foo() {
console.log("a");
return something().then(() => {
console.log("b");
return 42;
});
}



So looking at your function:



async function asyncFunc(){
for(i=0;i<10000000;i++){
}
console.log("3")
}


...we can see that all of the code in the function is in its initial synchronous part, and the promise it returns will be resolved with undefined.




So why do async functions have a synchronous part? For the same reason the executor function you pass into new Promise runs synchronously: So it can start its work right away.



Suppose we wanted to do an async wrapper around fetch where we expect a JSON response:



async function fetchJSON(...args) {
const response = fetch(...args);
return response.json();
};



If that didn't have a synchronous part (the call to fetch(...args)), it would never do anything and its promise would never be settled.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...