user603749
user603749

Reputation: 1763

Promise chaining with Q nodejs

I have this code here but I cannot figure out why the second FS.readfile() executes last. Basically I want to:

readFile(passwd)
  .then(console(textpasswd)
  .then(readFile(hosts).
  .then(console(texthosts);

But what happens is the readFile(hosts) executes last in the chain. I sense something is wrong with my deferring, but what?

Here is the code

module.paths.push('/usr/local/lib/node_modules');
var Q = require('q');
var FS=require('fs');
var deferred = Q.defer();
var p=deferred.promise;
FS.readFile("/etc/passwd", "utf-8", function (error, text) {
    if (error) {
        deferred.reject(new Error(error));
    } else {
        deferred.resolve(text);
    }
});
p.then(function (text) {
    console.log(text);
}).then(FS.readFile("/etc/hosts", "utf-8", function (error, text) {
        if (error) {
            deferred.reject(new Error(error));
        } else {
            deferred.resolve(text);
        }
    })
).then(function (text) {
    console.log(text);
});

Upvotes: 1

Views: 367

Answers (1)

user603749
user603749

Reputation: 1763

The deferred must obtain a new promise to continue the chain correctly. Also notice the first (function())() must be executed to return a promise although you don't need to do it this way. So here is my solution. (I cleaned it up a little):

module.paths.push('/usr/local/lib/node_modules');
var Q = require('q');
var FS = require('fs');
(function () {
    var deferred = Q.defer();
    FS.readFile("/etc/passwd", "utf-8", function (error, text) {
        if (error) {
            deferred.reject(new Error(error));
        } else {
            deferred.resolve(text);
        }
    })
    return deferred.promise;
})().then(function (text) {
    console.log(text);
}).then(function () {
    var deferred = Q.defer();
    FS.readFile("/etc/hosts", "utf-8", function (error, text) {
        if (error) {
            deferred.reject(new Error(error));
        } else {
            deferred.resolve(text);
        }
    })
    return deferred.promise;
}).then(function (text) {
    console.log(text);
}).then(function () {
    console.log('The End');
});

Upvotes: 2

Related Questions