使用Q保证在回调内返回值?

时间:2016-05-21 00:15:09

标签: javascript node.js asynchronous callback q

在我的代码中,我从数据库中获取hosts并在回调中处理它。如何退回此已处理的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!
    });
}

1 个答案:

答案 0 :(得分:0)

由于您要将其转换为基于承诺的功能,因此您需要使用它:

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!
    });
}

我这里没有catch()处理程序,所以由您来处理。