briancavalier/when.js — Issue #12: Guarantee future-turn resolutions
Author: briancavalier
Created: 2012-01-12 14:37:33+00:00
State: open

Currently, when.js doesn't guarantee future-turn promise resolutions. Callbacks might run immediately, in the current stack frame. The [Promises/A draft spec](http://wiki.commonjs.org/wiki/Promises/A) leaves it unspecified.

Here are some pros and cons I can think of:

### Pros

1. Removes all doubt as to whether a callback will run immediately or in a future turn. Currently, a callback registered with `when()` or `.then()` *might* execute immediately or in a future turn depending on the state of the promise (and potentially on the implementation if there are other promise implementations besides when.js in the app)
1. Protects variables in the current stack frame from being modified by a callback that captures them and might execute immediately. Related to #1, but wanted to call it out, specifically.

### Cons

1. Performance. This is the big downside in my mind. Even in environments that provide a fast alternative to `setTimeout()`, there will be a hit. For environments that *only* provide `setTimeout()`, the hit will be even more significant, due to low timer resolution.
1. Implementing this in an optimized, cross-environment way to take advantage of faster alternatives where available will obviously make the lib larger--not by a huge amount, but worth noting.

I've been using promises in JS heavily for over a year and honestly, I've never been bitten by, or even surprised by, a callback being called in the current turn when I didn't expect it to. I've also never run into a situation where I felt like I *needed* future-turn guarantees to implement something correctly.

All of my work has been in browsers, though, so I don't have a good feel for how important this issue is in a server environment, or how important the performance issue is there.

I'd love to hear what people think about this.