Promises in JS allow you to do async programming, as follows:
DoSomething().then(success, failure);
DoSomethingElse();
whenever i write the previous code it reaches DoSomethingElse() before it reaches success.
How is that possible? Isn’t JS a single threaded environment (not including web-workers)? is it done with setTimeout?
Yes, JavaScript is single-threaded, which means you should never block this single thread. Any long-running, waiting operation (typically AJAX calls or sleeps/pauses) are implemented using callbacks.
Without looking at the implementation here is what happens:
DoSomethingis called and it receivessuccessandfailurefunctions as arguments.It does what it needs to do (probably initiating long-running AJAX call) and returns
DoSomethingElse()is called…
Some time later AJAX response arrives. It calls previously defined
successandfailurefunctionSee also (similar problems)