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:
function when(x, onFulfilled, onRejected, onProgress) {
var p = Promise.resolve(x);
if (arguments.length < 2) {
return p;
}
return p.then(onFulfilled, onRejected, onProgress);
}
There is absolutely no difference between when(x,f)
and when(x).then(f)
.
(Given that .then(…)
does not care about its call stack or additional undefined
arguments)
Today, it is purely sugar, as when(x, f)
is shorter than its alternative or even the more efficient Promise.resolve(x).then(f)
. However, historically that was not always the case, the when
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 :-)