Basically, the point is that the then promise handler will not work until the current code stream completes execution and control returns to the runtime (in this case, Node).
This is an important feature of Promises / A + compatible promises because it provides predictability. Regardless of whether the solution immediately promises:
function getAPromise() { var Q = require('q'); var deferred = Q.defer(); deferred.resolve('SECOND'); return deferred.promise; } getAPromise().then(console.log); console.log('FIRST');
or resolves after 10 seconds:
function getAPromise() { var Q = require('q'); var deferred = Q.defer(); setTimeout(function () { deferred.resolve('SECOND'); }, 10000); return deferred.promise; } getAPromise().then(console.log); console.log('FIRST');
You can be sure that FIRST will always be registered first.
This is discussed in detail in chapters 2 and 3. You do not know JS - asynchrony and performance . Asynchronous operations, which are sometimes performed asynchronously and sometimes are executed synchronously, are called Zalgos, and they are not considered good.
It is important to note that the widely used promises in jQuery do not obey this behavior and have a number of other problems . If you find yourself with a jQuery promise, wrap it in the correct promise and continue:
Q($.ajax(...)).then(breatheWithEase);
Jlrishe
source share