cub01d cub01d - 6 months ago 18
Node.js Question

Returning value inside callback with a Q promise?

In my code, I grab

hosts
from a db and process it in a callback. How do I return this processed
hosts
?

var db = new sqlite3.Database(DB);
var all = Q.nbind(db.all, db);

function getHosts() {
return all('SELECT host FROM hosts ORDER BY host DESC', function(err, rows){
// rows: [ { host: 'z' }, { host: 'a' } ]
// transform into hosts: ['a','z']
var hosts = [];
var L = rows.length;

for (var i=0; i<L; i++) {
hosts.push(rows.pop().host);
}
// hosts = ['a','b', ... 'z']
return hosts; // <-- doesn't work!
});
}

Answer

Since you are converting it to a promise-based function, you need to use it as such:

function getHosts() {
    return all('SELECT host FROM hosts ORDER BY host DESC').then(function(rows) {
        // rows:  [ { host: 'z' }, { host: 'a' } ]
        // transform into hosts: ['a','z']
        var hosts = [];
        var L = rows.length;

        for (var i=0; i<L; i++) {
            hosts.push(rows.pop().host);
        }
        // hosts = ['a','b', ... 'z']
        return hosts;  // <-- doesn't work!
    });
}

I don't have a catch() handler here so its up to you to handle that somewhere.

Comments