简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM