I recently delved into the world of asynchronous programming in JavaScript and wanted to share some code for examination:
const myPromise = () => Promise.resolve('Success!');
function firstFunction() {
myPromise().then(res => console.log(res));
console.log('firstFunction');
}
async function secondFunction() {
console.log(await myPromise());
console.log('secondFunction');
}
firstFunction();
secondFunction();
The above code will yield the following output:
- firstFunction
- Success!
- Success!
- secondFunction
I am satisfied with the results and have a good understanding of why this sequence occurs:
- FirstFunction() is added to the call stack
- The promise is deferred on the event loop
- console.log('firstFunction') executes and displays (firstFunction)
- With the call stack empty, the resolved promise prints (Success!)
- Next, SecondFunction() enters the call stack
- Using async await means the code pauses at myPromise()
- (Success!) is then displayed
- Followed by (secondFunction)
If I modify the initial code as follows:
const myPromise = () => Promise.resolve('Success!');
function sayHi() {
console.log('hi');
}
function firstFunction() {
myPromise().then(res => console.log(res));
console.log('firstFunction');
}
async function secondFunction() {
console.log(await myPromise());
console.log('secondFunction');
}
firstFunction();
secondFunction();
sayHi();
I would anticipate the following output:
- firstFunction
- Success!
- Success!
- secondFunction
- hi
However, the actual output is:
- firstFunction
- hi
- Success!
- Success!
- secondFunction
Could someone please clarify why this behavior is observed?