Why are Q.js promises asynchronous after they have been resolved?

If I have the following:

var deferred = Q.defer();

deferred.resolve();

var a = deferred.promise.then(function() {
    console.log(1);    
});

console.log(2); 

... why do I see 2 and then 1 in the console?

I understand that this conclusion is correct according to the Promises specification, which says to call the function of the next tick (e.g. setTimeout()), even if it is already enabled, but I don’t understand why.

I would like to have code that calls thenin a series of Promises synchronously, assuming all Promises have been resolved.

My real use is that I am trying to use the Angular implementation $q, and I want all the callbacks to be thenexecuted in the same loop $digest, so that I don't get any unnecessary subsequent loops $digest.

+6
2

- .

promises, , . , promises, .

. , . , .

, .

+2

, . , , , , .

JS , , , - . - , , . , - , .

, - .

. , , .

, , , . , , . .

, , , , . , , . .

, , , - - (), - , . . .

, - , . , . , , , , , .

, , , , , , , , , . , . , , .

, . , , , , , , - . , 50,5 , - , 50 . , 50 , . , , , , .

, /. , , .

, . , , async/await, . , .

-3

All Articles