Cameron Martin
Cameron Martin

Reputation: 6012

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?

Upvotes: 4

Views: 2755

Answers (2)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276396

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.

Upvotes: 6

Scott Rippey
Scott Rippey

Reputation: 15810

What if you use the new Promise constructor to resolve the promise?

return new Promise(function(resolve, reject) {
    resolve(faye_client);
});

Upvotes: 0

Related Questions