On Medium, I red an interesting article that explains a certain problem. However, this article does not provide a sufficient solution.
const asyncOperation = fetch('something.com');
asyncOperation.then((resolvedValue) => console.log("Horse A"));
console.log("Horse B")
Results
Horse B
Horse A
Explanation
This is one that people consistently get wrong. It’s a common misconception that calling .then on a Promise will cause JavaScript to immediately invoke the function inside of the .then function.
After all, you clearly have access to resolvedValue before calling console.log("Horse B") , or at least that’s the order in our script. It’s even named such that once you have your Promise object, you can THEN see what’s inside of it. But this is misleading. The .then method should really be renamed to .wheneverThisValueGetsResolved (unfortunately, not as sexy).
Here is what JavaScript is really doing: when we call fetch , we get back a Promise object. This Promise object actually has two hidden properties, value and onFulfilled. When we push fetch on to the call stack, it gets sent off to the browser APIs and does its work in the background, similar to the setTimeout method. While it’s doing this work, all subsequent synchronous operations are performed, like before. But wait, we explicitly called .then on our Promise before moving onto console.log! Well…this is where the two hidden properties value and onFulfilled come into play.
When our background operation is finished, it updates the value property of our Promise. When this happens, this value is automatically passed into the onFulfilled property. Okay, but what’s so special about onFulfilled ? The answer is that the function that you passed into the .then method actually gets pushed onto the onFulfilled property of the Promise. In other words, console.log("Horse A") is actually pushed on to the onFulfilled property of our Promise. When the Promise finally resolves, (i.e., we get back our value), THEN the function(s) in onFulfilled gets to be executed. This is why .then should really be named .wheneverThisValueGetsResolved.
TL;DR: the function that you write inside of the .then method only gets executed when the Promise itself is resolved. Not immediately upon calling .then on the Promise.
My Question How do I make JavaScript to immediatly invoke the function inside of the .then function ? I often have to deal with this kind of problem that JS behaves async when i do not need it.
What should happen in the above mentioned code to create the following result:
Horse A
Horse B