`when(foo, f)` 和 `when(foo).then(f)` 有什么区别

What is the difference between `when(foo, f)` and `when(foo).then(f)`

我正在查看一些使用 when.js 的现有代码。出现几次的模式是:

return when(someBigFunction(), function() {
  doSomeMoreProcessing();
  if (maybe) {
    throw someError;
  }
});

我想他们在这里使用 when 的原因是他们当时不确定 someBigFunction() 是否会 return 做出承诺。

以上和

在语义上有区别吗?
return when(someBigFunction()).then(function() {
...
});

一般来说,示例不会使用承诺的 return 值(也就是说,它是 function() { 而不是 function(x) {) .

API 文档提供了这个:

所以我怀疑没有区别,但也许我遗漏了一个微妙之处?

查看 implementation itself 确实解决了这个问题:

function when(x, onFulfilled, onRejected, onProgress) {
    var p = Promise.resolve(x);
    if (arguments.length < 2) {
        return p;
    }

    return p.then(onFulfilled, onRejected, onProgress);
}

when(x,f)when(x).then(f)之间完全没有区别

(鉴于 .then(…) 不关心其调用堆栈或额外的 undefined 参数)

今天,它是纯糖,因为 when(x, f) 比它的替代品更短,甚至比更有效的 Promise.resolve(x).then(f)。然而,历史上情况并非总是如此,when 函数提供了一个重要的库入口点,例如在 this version (10/2011) or the initial commit (5/2011).
有趣的还有commit Architectural decision that when() should always return a promise (result, 9/2011)。开创性的工作,真的:-)