質問

When I call below function and show data at view of my ejs. There is no data at the first time of loading after the server start. But can get datas from second times of loading. That just only empty list on first time of loading after the server start. What is this matter? I am using redis as database. I also faced same error in using postgreSQL and sovled with

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

but can't use that code now.

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 = [];

};
役に立ちましたか?

解決

I solved as the below code by using setTimeout function. I know that is not the great answer but now can solved my error indeed.

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

};
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top