单个 resolver/promise 的多个生产者

Multiple producers for a single resolver/promise

在 Q 文档中有这一行:

"You can give the resolver to any number of producers and whoever resolves the promise first wins. Furthermore, none of the producers can observe that they lost unless you give them the promise part too."

我真的不明白那是什么意思。这是在您手动构建 promise 时使用的吗?有人可以给我举个例子吗?

Is this for when you are constructing a promise by hand?

确切地说,您可以使用 deferred 或 promise 构造函数创建一个 promise,多次调用 resolve 但只有第一次有效。例如:

var p = new Q.Promise(function(resolve){
    resolve(1);
    resolve(2);
    resolve(3);
    resolve(4);
    resolve(5); // can also pass `resolve` around.
});

p.then(function(result){
    // always 1, all other calls had no effect.
});

这让您可以构建有趣的东西,例如让我们构建一个 race 函数,该函数 returns 两个承诺的第一个解析结果(为简洁起见省略了错误处理):

function race(p1, p2){
    return new Promise(function(resolve){
        p1.then(resolve);
        p2.then(resolve);
    });
}

哪个 promise 先准备就绪,哪个会解决,例如:

race(tryToGetFromFirstAPI(), tryToGetFromSecondAPI()).then(function(result){
   // resolves as soon as the "fastest" resolved, with the result
});

是的,我最近对那句话不以为然。不幸的是,您需要先理解 Deferreds/Promises 才能理解其实际含义。

对我来说,问题是从介绍句开始的:

Deferreds are cool because they separate the promise part from the resolver part. So:

这是一种误导,因为 Deferreds 实际上并没有 分离 这些组件——更准确的说法是它们 组合 它们,但允许如果需要他们分开。

即兴发挥,更好的措辞是:

Deferreds [are cool because they] include the means to derive a Promise and include, in the form of executable methods, the means to resolve or reject, all wrapped up in a single object. So:"

"You can give the promise to any number of consumers ..."开头的句子有点啰嗦,其他都还好。

但是以 "You can give the resolver to any number of producers ..." 开头的句子最好读作:

The resolve and/or reject methods are readily detachable allowing you, for example, to pass them to any number of producers and whoever resolves/rejects first wins; furthermore, by passing the detached methods and not the Deferred itself (and hence its Promise), none of the producers can observe whether they won or lost."

第三个声明也可能包括在内:

A Deferred can be passed in its entirety, complete with its means to resolve/reject and to derive a Promise."

事实上,以上所有 都可以 ,只要稍加技巧,也可以通过 new Promise(synchronousSettlerFunction) 构造和外部变量来实现。

还应该说,这样的说法是可以反复修改和改进的。我上面的尝试花了我 15 分钟,所以我不会假装他们是硬道理。