【问题标题】:Returning value inside callback with a Q promise?使用 Q 承诺在回调中返回值?
【发布时间】:2016-09-18 08:42:12
【问题描述】:

在我的代码中,我从数据库中获取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!
    });
}

【问题讨论】:

    标签: javascript node.js asynchronous callback q


    【解决方案1】:

    由于您要将其转换为基于 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() 处理程序,所以由你来处理。

    【讨论】:

    • 谢谢!正是我想要的。
    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 2016-06-15
    • 2016-10-24
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多