I was presented this coding question on a job application and I want to learn and understand, so here is the code question and then I will provide my interpretation and ask the SO community to elaborate/correct my interpretation:
async function someFunction() {
console.log('someFunction'):
}
console.log('start');
someFunction();
console.log('end');
The output here is arguably unpredictable in my opinion, the order now, simply because we know the implementation of someFunction
starts with a console.log
will be:
- start
- someFunction
- end
I have run this code in my browser and I do see that it always runs in this order. I am just not sure as to the reason why.
Reading online, "forgetting" the await
keyword for the execution of async someFunction
the function will still execute asynchronously.
My reasoning is that, albeit someFunction
is async and returns a promise, the first line of execution of someFunction will occur before console.log('end'). I am not sure why many developers think that these are good hiring questions, perhaps they are. I just find them to be trick questions that are not real world. In the real world, the promise returned by someFunction
would be handled, for example:
console.log('start');
await someFunction();
console.log('end');
I would appreciate an explanation of this code please.