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.
async functions will halt at the firstawait. Since there isn't any it's basically the same as a normal function.asyncfunctions that aren't awaited. In fact, you can'tawaitin top level scope (but you canthenit).awaitmaking a difference. If you doresult = await getResult(); array = array.concat(result)that's different toarray = array.concat(await getResult())even if normally inlining a variable will not make a difference. More generally, you can have the same problem withmyVar = myVar + await getResult()- anything that mutates a variable and different timings of when it happens lead to different results.