使用 Q 承诺在回调中返回值?

Returning value inside callback with a Q promise?

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

由于您要将其转换为基于 promise 的函数,因此您需要这样使用它:

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() 处理程序,因此您可以在某个地方处理它。