What Will Be The Output Of This Node/es6 Code And Why?
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
Solution 1:
The order here is completely deterministic it will always be start
-> someFunction
-> end
:
asyncfunctionsomeFunction() {
console.log('someFunction');
}
console.log('start');
someFunction();
console.log('end');
This is because only an await
will pause the execution of an async function. Any code before an await
will be executed synchronously, while any code after an await
will only run after the promise await
ed is resolved:
asyncfunctionsomeFunction() {
console.log('someFunction - before await');
awaitotherFunction();
console.log('someFunction - after await');
}
asyncfunctionotherFunction() {
console.log('otherFunction');
returnnewPromise(function(resolve, reject) {
setTimeout(function() {
console.log('promise resolved');
resolve();
}, 0);
});
}
console.log('start');
someFunction();
console.log('end');
This can come into play if you have non-trivial async functions that might do multiple actions and it matters what order they are in:
//sample shared variablelet counter = 1;
asyncfunctionsomeFunction() {
console.log('someFunction - before await counter is:', counter);
let awaitResult = awaitotherFunction();
console.log('someFunction - after await counter is: ', counter, '\nawaited function returned: ', awaitResult);
}
asyncfunctionotherFunction() {
returnnewPromise(function(resolve, reject) {
setTimeout(function() {
resolve(counter);
}, 0);
});
}
someFunction();
counter += 1;
This is a dumbed down example but it showcases what can happen - if you read someFunction
you could assume that counter
has the same value both times. But that's not correct, since the mutation of the variable happens after the first read and before the second one. The await
is what makes the difference.
Post a Comment for "What Will Be The Output Of This Node/es6 Code And Why?"