I have the following code, which does not work as I expect.
const bar = () => console.log('bar')
const baz = () => console.log('baz')
const myPromise = new Promise((resolve, reject) =>
resolve('should be right after baz, before bar')
);
const foo = () => {
console.log('foo')
setTimeout(bar, 0)
myPromise.then(resolve => console.log(resolve))
baz()
}
foo()
console.log('before bar')
The result:
foo
baz
before bar
should be right after baz, before bar
bar
According to what's written in https://nodejs.dev/ , promise resolve will happen right after the function.
Promises that resolve before the current function ends will be executed right after the current function.
So I expect 'should be right after baz, before bar' to happen right after the end of foo()
, before console.log('before bar')
.
Can someone explain why it doesn't?