1

I try to implement a state machine using node js. to simplify the callbacks I'm using q and promises. In some cases calling functions on a specific state does nothing. but to use it in control flow, I need a resolved promise.

So my state looks like this.

// onstate.js
module.exports = function(){
  this.switchOn = function(){
    var deferred = Q.defer();
    deferred.resolve();
    return deferred.promise;
  };
  this.switchOff = function(){
    var deferred = Q.defer();
    object.switchOff()
      .then(function(result){
          // changing to off-state
          deferred.resolve();
        },
        function(err){
           deferred.reject(err);
        });
    return deferred.promise;
  };
}

The switch off function is like described in Q docu. but what about the switchon function? I wand to call:

currentState.switchOn().then(foo(), bar());

Do I really have to create a deferred resolving immediately or can the same behavior be achieved using a more simple code?

Martin H.
  • 1,086
  • 1
  • 17
  • 28

2 Answers2

2

You can create a resolved promise with Q(value). In your specific case, just Q().

Docs: https://github.com/kriskowal/q/wiki/API-Reference#qvalue

pablochan
  • 5,625
  • 27
  • 42
0

I need a resolved promise.

The Q function does that, in ES6 it would be Promise.resolve(…).

my code looks like this

It heavily uses the deferred antipattern! You could just do

module.exports = function() {
  this.switchOn = function() {
    return Q(); // passing `undefined`
  };
  this.switchOff = function() {
    return object.switchOff();
  };
};

and still use it with currentState.switchOn().then(foo, bar); (notice I'm not passing calls to then).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Ok, clear, if the second part just returns the other promise. But to simplify it // changing to off-state in my sample is even a placeholder for doing some stuff (other promises and some local stuff too), so it's not that simple in real life. So is it an antipattern then anyway? And if so, how to do it better. – Martin H. Apr 13 '15 at 07:23
  • Yes. Of course, without seeing the actual code I cannot really tell, but usually the use of deferreds is an antipattern. The "some local stuff" should return promises as well, and you can combine them using `then`. – Bergi Apr 13 '15 at 14:12