如何从 when.js 承诺中干净地提取回调?

How to cleanly extract a callback out of a when.js promise?

我需要将回调传递给签名为 function('ui', {foo: bar, callback: callbackfn}) 的函数。我要传递的功能是 When.js 承诺。

我想到的最好的:

var d = when.defer();
var p = when(d);
var q = p.then(function() {
    return loadItem(newCatalogItem, name, fileOrUrl);
});

ConfirmationMessage.open('ui', { callback: d.resolve });

return q;

这行得通(使用延迟来防止立即执行,然后将 resolve 函数作为回调传递),但似乎有点令人费解。

有没有更简洁的方法?

我想你只想 promisify that ConfirmationMessage.open method (see also the when.js docs here and there),然后像使用 promise 函数一样使用它,链接 then 调用它。

对于您的具体示例,可能是(使用可移植的 promise 构造函数):

return when.promise(function(resolve) {
    ConfirmationMessage.open('ui', { callback: resolve });
}).then(function(confirmResult) {
    return loadItem(newCatalogItem, name, fileOrUrl);
});