0

当我调用下面的函数并在我的 ejs 视图中显示数据时。服务器启动后第一次加载没有数据。但是可以从第二次加载中获取数据。服务器启动后第一次加载时只有空列表。这是什么问题?我正在使用 redis 作为数据库。我在使用 postgreSQL 时也遇到了同样的错误并解决了

client.on('end', function(){
   fn(_datas);
}. 

但现在不能使用该代码。

getAllDatas = function(fn){
    client.smembers('db:contact:all', function(err, _uid){
        if(err)
            throw err;
        else{
            for(var i = 0; i < _uid.length; i++){
                    client.hgetall('db:contact:' + _uid[i], function(err, reply){
                    if(err)
                        throw err;
                    else{
                        _datas.push(reply);
                    }
                }); 
            }
        }
    });
    fn(_datas);
    _datas = [];

};
4

1 回答 1

0

我通过使用setTimeout函数解决了以下代码。我知道这不是很好的答案,但现在确实可以解决我的错误。

getAllDatas = function(fn){
    var _datas = [];
    client.smembers('db:contact:all', function(err, _uid){
        if(err)
            throw err;
        else{
            for(var i = 0; i < _uid.length; i++){
                    client.hgetall('db:contact:' + _uid[i], function(err, reply){
                    if(err)
                        throw err;
                    else{
                        _datas.push(reply);
                    }
                }); 
            }
        }
    });
    setTimeout(function(){
       fn(_datas);
    }, 100);

};
于 2013-11-22T04:58:05.490 回答