简体   繁体   中英

Running sequential functions in Q Promise (Node.js)

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.

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 .

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