I need to pass a callback to a function whose signature is function('ui', {foo: bar, callback: callbackfn})
. The function I want to pass is a When.js promise.
The best I've come up with:
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;
This works (using a deferred to prevent immediate execution, and then passing the resolve
function as the callback), but seems a bit convoluted.
Is there a cleaner way?
I think you want to just promisify that ConfirmationMessage.open
method (see also the when.js docs here and there), and then use it like a promise function, chaining then
calls onto it.
For your specific example, that could be (using the portable promise constructor):
return when.promise(function(resolve) {
ConfirmationMessage.open('ui', { callback: resolve });
}).then(function(confirmResult) {
return loadItem(newCatalogItem, name, fileOrUrl);
});