I'm looking at some existing code that uses when.js
. A pattern that appears a few times is:
return when(someBigFunction(), function() {
doSomeMoreProcessing();
if (maybe) {
throw someError;
}
});
I imagine the reason they use when
here is they weren't sure at the time whether someBigFunction()
would be returning a promise or not.
Is there a difference, semantically between the above and:
return when(someBigFunction()).then(function() {
...
});
Generally the examples don't make use of the return value of the promise (that is, it's function() {
not function(x) {
)
.
The API docs offer this:
when(x,f)
: Get a trusted promise by transforming x with fthen
: Transforms a promise's value by applying a function to the promise's fulfillment value.
So I suspect there is no difference, but maybe I'm missing a subtlety?
Looking at the implementation itself does clear this up:
There is absolutely no difference between
when(x,f)
andwhen(x).then(f)
.(Given that
.then(…)
does not care about its call stack or additionalundefined
arguments)Today, it is purely sugar, as
when(x, f)
is shorter than its alternative or even the more efficientPromise.resolve(x).then(f)
. However, historically that was not always the case, thewhen
function provided an important entry point to the library, e.g. in this version (10/2011) or the initial commit (5/2011).Interesting is also the commit Architectural decision that when() should always return a promise (result, 9/2011). Groundbreaking work, really :-)