Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, then 1 in the console?

I understand this output is correct according to the Promises spec, which says to call the function on the next tick (e.g. setTimeout()), even if it is already resolved, but I don't understand why.

I would like to have code that calls then on a series of promises synchronously, assuming that all the promises have been resolved.

My real use case is that I am trying to use Angular's implementation, $q, and I want all of the then callbacks to execute in the same $digest cycle, so that I don't get unnecessary subsequent $digest cycles.

like image 461
ChrisBellew Avatar asked Jul 22 '14 07:07

ChrisBellew


People also ask

Are promises in JavaScript asynchronous?

A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed.

Are promises always asynchronous?

In testing I've found that JavaScript Promises are always asynchronous regardless of whether or not they contain any asynchronous functions in their chain. Here is some code that shows the order of operations in console.

Are JS promises synchronous?

JavaScript is Synchronous Spoiler: at its base, JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time.

What is a promise in asynchronous programming?

A promise is an object returned by an asynchronous function, which represents the current state of the operation. At the time the promise is returned to the caller, the operation often isn't finished, but the promise object provides methods to handle the eventual success or failure of the operation.


1 Answers

Answer is consistency.

In real code, you don't have promises that are always immediately resolved when created, they would be pointless. So you have promises that sometimes may be immediately resolved.

In that case, you don't want to have a different flow. You want always the same, predictable flow. So you want the next function to be always called on next tick.

Don't use a promise when you don't need one.

like image 111
Denys Séguret Avatar answered Sep 29 '22 17:09

Denys Séguret