0

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?

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
  • "*the function is a promise*" doesn't make much sense. Do you mean you have a promise for a function? – Bergi Feb 25 '16 at 23:04
  • Does `ConfirmationMessage.open` use the node callback convention with error arguments? Or do you really want to fulfill in every case? – Bergi Feb 25 '16 at 23:06
  • it either calls the callback with no arguments (success), or it doesn't call it. – Steve Bennett Feb 26 '16 at 01:02

1 Answers1

1

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);
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Ok, nice. Unfortunately stuck with using when.js 1.7.1 (no `when.promise()`) but this helped structure it more cleanly regardless. – Steve Bennett Feb 26 '16 at 01:02