Chainable, Promise-based Class Interfaces in JavaScript

不问归期 提交于 2019-12-05 18:45:30

What you have now

What you have now is actually pretty nice. Since you're caching the result of asyncInit in a promise and everyone waits for the same promise - it's impossible for any of the code in those functions to run before the promise has finished.

function publicMethod_One() {    
  promise // the fact you're starting with `promise.` means it'll wait
    .then( doStuff )
    .catch( reportInitFailure );
}

So rather than forcing people to wait in order to use publicMethod_One they already can call it right away and the methods like doStuff will only execute the promise has resolved.

A fluid interface

Well, like you noticed your code has a major issue, there is no way for a given method to know when to run or a way to sequence methods - you can solve this in two ways:

  • Create a fluid interface that returns this on every action and queues the promise.
  • Return the promise from each async call.

Let's look at the two approaches:

Fluid interface

This means that all your methods return the instance, they must also queue so things don't happen 'at once'. We can accomplish this by modifying promise on each call:

function publicMethod_One() {    
  promise = promise // note we're changing it
    .then( doStuff )
    .catch( reportInitFailure );
  return this; // and returning `this`
}

You might also want to expose a .ready method that returns the current promise so the sequence of operations can be waited for from the outside:

function ready(){
    return this.promise;
}

This can enable things like:

var ready = new WhizBang().publicMethod_One().publicMethod_One().ready();
ready.then(function(){
     // whizbang finished all operations
}); // can also add error handler

Returning thenables

In my opinion this is the simpler approach, all your methods return the promise they create so they can individually be waited for:

function publicMethod_One() {    
  return promise // note we're returning and not changing it
    .then( doStuff )
    .catch( reportInitFailure );
}

This is nice because the async operation is exposed outside.

Chaining is possible since you're using bluebird with .bind as such:

var whiz = new WhizBang();
var res = Promise.bind(whiz).then(whiz.publicMethod_one)
                            .then(whiz.publicMethod_one);
res.then(function(){
     // all actions completed, can also use return values easier.
});

But the advantage is it easier to reason about from the outside - for this reason I prefer this approach personally. Personally I always prefer to return meaningful data than to change internal state.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!