Cameron Martin Cameron Martin - 1 month ago 8
Javascript Question

How do I create a javascript promise which resolves to a thenable?

I'm working with the faye browser client using promises, and I have a function that creates a faye client after doing something asynchronous, like so:

function fayeClient() {
return doSomethingAsychronous().then(function() {
var faye_client = new Faye.Client('http://localhost/faye');
return faye_client;
});
}


and I want to use it like so:

fayeClient().then(function(faye_client) {
// do something with faye_client
});


The problem is,
faye_client
is also a thenable, which means that the promise returned by
fayeClient
resolves to the value that
faye_client
'resolves' to.
However, I want the promise to resolve directly to
faye_client
.

I can't even manually wrap the value in a promise using
Promise.resolve(faye_client);
, since the same promise resolution procedure is used.

I think this could indicate a misuse of thenables on faye's part, since
faye_client
does not represent a value which is not yet known.

Is there any way to make a promise which resolves to a value which is also a thenable?

Answer

Instead of returning faye_client directly wrap it in an object. It's ugly but it's kind of your only choice with A+ promises:

return {client: faye_client}; // no longer a thenable

Some alternative promise implementation expose a .then or .chain that doesn't recursively assimilate but honestly I'd avoid those.

Comments