Cameron Martin Cameron Martin - 1 year ago 75
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,
is also a thenable, which means that the promise returned by
resolves to the value that
'resolves' to.
However, I want the promise to resolve directly to

I can't even manually wrap the value in a promise using
, since the same promise resolution procedure is used.

I think this could indicate a misuse of thenables on faye's part, since
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download