6

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.

2

2 Answers 2

2

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.

9
  • 2
    The technical term I believe is "Don't release Zalgo", a method must always either be asynchronous or synchronous otherwise you get really weird race conditions that will make you cry. Commented Jul 22, 2014 at 7:53
  • 1
    @BenjaminGruenbaum I didn't know the technical term. Thanks for enlightenment Commented Jul 22, 2014 at 7:55
  • Thanks for your answer. Maybe I don't want a promise. I want a neat way of requesting an HTTP resource, providing it to the initial caller, and then caching it to be provided to subsequent callers. I have used a promise that does an HTTP request, and I am storing the promise object so that subsequent callers can pass a callback to 'then', and have it called ASAP, preferably before the next tick (I have other behavior which is called on next tick, and I want this code to have been satisfied before that other behavior runs). Do you think my use of promises is inappropriate? Thanks again. Commented Jul 22, 2014 at 7:59
  • 2
    @MariuszNowak In my opinion, this is a very bad idea. The very few occurences where it could maybe lead to better performances don't make up for the difficulty to analyze the code and the subtle bugs it will lead to. Commented Jul 24, 2014 at 8:29
  • 2
    @MariuszNowak come on... 33 issues in several years is not a lot of users... I can get your stance on .done (which, I still believe is a redundant artifact of a naive implementation for doing something the library or native promises should do) - but releasing Zalgo? Doing this sort of sync dispatch is a horrible idea and jQuery promises are infamous for this. I've personally had to deal with several such situations with jQuery promises (that exhibit this behavior)... it's definitely not a 'non issue'. Commented Jul 24, 2014 at 13:24
-3

It's a design mistake based on a set of opinions and assumptions. It has become latched because it was rushed out without full technical verification in a design by committee process that also had the back pressure of a lot of vendors implementing their own already with the same mistake making it hard to backtrack.

Once a standard goes out for JS to the web it can be revoked, even if it's broken with the idea being that webpages shouldn't break. If someone wrote a page today, then died, it should be possible to still view it in your browser in five years. It would be very problematic if when browsing the web you kept bumping into pages that didn't work with your browser.

In very simple use cases it doesn't do much harm and removes confusion about whether something is maybe async.

For increasingly non-trivial use cases it causes increasingly more harm and adds confusion. Initially it appears to make it easier to reason about your code but it sacrifices the less trivial usage for the least trivial usage.

It's overall much easier to reason about your code if it doesn't run things in the next tick that don't need to be async at all. This is a case of choosing to damage the language at level two to cater to level one users, at the expense of level two users and above, rather than working to help ascend level one users to level two users. It's a condescending or pessimistic design decision.

There's an intermediate solution where it's possible to run each task as if it runs after the current code runs to completion but things are scheduled in the correct order. This hasn't been implemented and it's also debatable as compromises don't always produce the best solutions. This compromise produces performance issues for direct return callstacks.

The way promises work means that the forward callstack is depth first and run to completion (isolated) but the return callstack is breadth first and run in pieces interleaved with other return callstacks. These are two radically different concept and behaviours. Traditionally with callbacks both run in the same way.

It also means you can't naively replace callbacks with promises or anything based on promises. Callbacks give you more options which promises take away. If you replace callbacks with promises without taking this difference into account you can create code that has stability issues and potential security issues as well since this behaviour of unordering events can cause the current code flow to unexpectedly jump track.

You can't rely on order which means there are cases with promises where if you ask for lots of things when you get them back you have to double check they're the thing you asked for where as you would not need to do this with callbacks. You may also need to buffer and reorder events which you would not need to do with callbacks. It can make benchmarks unreliable as well if you're not careful to isolate the two things being run.

This can also create serious performance bottlenecks that you can't always easily prevent. If you use promises a hundred returned results returned at once from a single event to an iterator, each taking one second per return call and their promise resolve depth is two, they'll all be broken into half with the first halves all run then the second halves. That means it will take 50.5 seconds before anything can finish where as with callbacks after 50 seconds half of them would already be finished. If the result of the task is passed along to another external service for processing then it leaves that service standing idle for 50 seconds when it could have been processing your results. This makes the promises terrible for when you want both low latency and high throughput under services that take load demonstrating the weakness of the design.

Not being able to naively replace callbacks with promises is one of the most devastating consequences of this design mistake which is also carried over to async/await. If you want to convert a callback library you can't simple change the syntax, you must carefully scrutinise the semantics at every point.

There is no plan to fix this. You can create your own promises and generators can be used to provide the same kind of syntax as async/await but with the same predictable and high performance behaviour of callbacks. You may however have problems playing nice with other libraries that still rely on native promises.

11
  • Downvoted because a) I disagree with the content and b) it comes off as a rant, but could you please expand on what you mean by "It hasn't been implemented that things are scheduled in the correct order" and "You can't rely on order"? Maybe with examples?
    – Bergi
    Commented Oct 1, 2019 at 22:46
  • The content is based on studying the ES specification and then testing that. It's all real unfortunately for that. You raise a point though. I haven't tested it with Q. I've just assumed they conform to the same standard for interoperability.
    – jgmjgm
    Commented Oct 1, 2019 at 22:53
  • 1
    My point is not about Q vs native promises, my point is that your post is really unclear about what code you are having performance/scheduling problems with.
    – Bergi
    Commented Oct 1, 2019 at 23:06
  • 2
    No. The answer to the question is "It does that because that's how it is specified" and possibly "It was designed like that because…". Your post, in contrast, only states "I heavily disagree with how it works and consider it as a bad design" (to put it lightly).
    – Bergi
    Commented Oct 1, 2019 at 23:26
  • 1
    The thing is, I'm having trouble following through the performance part. What do you mean by "promise resolve depth of two"? And how would promises ever have a scheduling time of around 50s, if they were used with proper non-blocking code for concurrent tasks?
    – Bergi
    Commented Oct 1, 2019 at 23:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.