0

I have two functions that return a Q Promise:

var q = require('q');

var get1 = function () {
    var deferred = q.defer();
    deferred.resolve('hello world');

    return deferred.promise;
};

var get2 = function () {
    var deferred = q.defer();
    deferred.resolve('hello world 2');

    return deferred.promise;
};

I can call each of them like this:

get1().then(console.log,console.error);

Right now, I want to sequentially call them. How?

I tried this:

q.fcall(self.get1)
        .then(self.get2);

but in this method how can I pass parameters to functions? How can I get resolve or reject values for each of them?

I want to run them sequentially even though one of them has an Async process in its body.

Brian Glaz
  • 15,468
  • 4
  • 37
  • 55
Fcoder
  • 9,066
  • 17
  • 63
  • 100

1 Answers1

1

If you use the chained response, that the value of the first Promise will get passed to the second through the continuation, so your get2 should accept an argument:

var get1 = function () {
    var deferred = q.defer();
    deferred.resolve('hello world');

    return deferred.promise;
};

var get2 = function (result) {
    var deferred = q.defer();
    deferred.resolve(result + 2);

    return deferred.promise;
};

//Then you can use it like so
get1().then(get2).then(console.log.bind(console), console.error.bind(console));

Also as a side note you should avoid using the defer api where possible, since it is considered an anti-pattern.

paulpdaniels
  • 18,395
  • 2
  • 51
  • 55
  • 2
    I agree about the usage of `defer`. If you have Node.js 4+ you can use Promises now `new Promise(function (resolve, reject) {});` – Cameron Sep 21 '15 at 21:12
  • 2
    The version number confused me briefly, I didn't realize node had finally reintegrated with io.js. Good point, though the OP did seem to be using `Q` specifically. – paulpdaniels Sep 21 '15 at 21:18
  • @paulpdaniels: thanks.can you explain what you say about avoiding defer? with an example if possible – Fcoder Sep 21 '15 at 21:21
  • 2
    @Fcoder - Take a look at this question: [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – sdgluck Sep 21 '15 at 21:29
  • In this case it's not really the antipattern, since your deferreds are not resolved from a promise. They're just created in those functions, which is fine. Of course resolving them immediately is a bit odd, and in this particular case you should have used `return Q("hello world");` and `return Q(result + 2)` – Bergi Sep 22 '15 at 20:54