3

アイテムに関するコメントを保存できるように、作成中の Node.js アプリケーションと redis データベースをリンクしようとしています。接続を処理するために node_redis ライブラリを使用しています。データベースからコメントを取得しようとすると、「[true]」のみが返されます。テスト目的で、すべてを 1 つのメソッドに詰め込み、値をハードコードしましたが、それでも「[true]」を受け取ります。

exports.getComment = function (id){

var comments = new Array();

rc.hmset("hosts", "mjr", "1", "another", "23", "home", "1234");

comments.push(rc.hgetall("hosts", function (err, obj) {

    var comment = new Array();

    if(err){
        comment.push("Error");
    } else {
        comment.push(obj);
    }

    return comment;
}));

return comments;

}

チュートリアルに従ってコードを更新した結果は次のとおりです。

コメントの取得:

exports.getComment = function (id, callback){

  rc.hgetall(id, callback);

}

コメントの追加:

exports.addComment = function (id, area, content, author){

//add comment into the database
rc.hmset("comment", 
         "id", id, 
         "area", area, 
         "content", content,
         "author" , author,
         function(error, result) {
            if (error) res.send('Error: ' + error);
         });

//returns nothing

};

レンダリングするコード:

var a = [];
require('../lib/annotations').addComment("comment");
require('../lib/annotations').getComment("comment", function(comment){
    a.push(comment)
});
res.json(a);
4

2 に答える 2

2

Node.js は非同期です。つまり、非同期で redis を実行し、コールバック関数で結果を取得します。

先に進む前に、このチュートリアルを読んで完全に理解することをお勧めします: http://howtonode.org/node-redis-fun

基本的に、この方法は機能しません。

function getComments( id ) {
    var comments = redis.some( action );
    return comments;
}

しかし、それはこのようでなければなりません:

function getComments( id, callback ) {
    redis.some( action, callback );
}

このように、次のように API を使用します。

getComments( '1', function( results ) {
    // results are available!
} );
于 2012-06-21T13:27:16.327 に答える
0

以下のように addComment への呼び出しが行われると、問題は実際の Redis-Node ライブラリ内にあります。

require('../lib/annotations').getComment("comment", function(comment){
    a.push(comment)
});

この呼び出しには、コールバック関数の引数がありません。最初の引数はエラー レポートで、すべて問題がなければ null を返します。2 番目の引数は実際のデータです。したがって、以下の呼び出しのように構成する必要があります。

require('../lib/annotations').getComment("comment", function(comment){
    a.push(err, comment)
});
于 2012-06-26T14:19:35.287 に答える