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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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).

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.