2014-06-23 1 views
0

여기 간단한 HTTP 서버가 있습니다. foo()이 호출되면 키를 기반으로 값을 가져옵니다. 그러나이 호출 될 때 foo(key, redisClient) 밝혀, 그것은node.js에서 다음 명령문으로 진행하기 전에 함수 호출을 완료하고 리턴 할 수 있습니까?

내가 foo는

내부입니다 그리고 바로이 시간 비동기 redis.get으로

x is null 

를보고 계속 인쇄 통화가 끝났으며 지금은 알겠습니다.

foo에서 돌아 오는 정보 : 1

이는 내가 기대했던 값입니다. 하지만 지금까지 내 오류 검사가 끝났으며 이미 HTTP 응답에 오류가 기록되었습니다. 주 서버 스레드에서 다른 작업을 진행하기 전에 실제로 foo()에서 올바른 반환 값을 얻어 x에 저장하도록하려면 어떻게해야합니까?

var http = require('http'); 
var redis = require("redis"); 
http.createServer(function (req, res) { 

    var x = null; 
    var key = "key"; 
    var redisClient = redis.createClient(); 

    x = foo(key, redisClient); 

    if(x == null) 
    { 
     // report error and quit 
       console.log('x is null'); 
       // write error message and status in HTTP response 
    } 
    // proceed 
     console.log('Proceeding...'); 
     // do some stuff using the value returned by foo to var x 
     // ......... 
     // ......... 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello World\n'); 
}).listen(1400, '127.0.0.1'); 
console.log('Server running at http://127.0.0.1:1400/'); 


function foo(key, redisClient) 
{ 
    console.log('I am inside foo'); 
    redisClient.get(key, function(error, result) { 
     if(error) console.log('error:' + error); 
     else 
      { 
        console.log('About to return from foo with result:' + result); 
        return result; 
      } 
    } 
} 

답변

1

redisClient.get()의 호출은 foo()의 반환에 전달되지 않습니다. 콜백에서 다시 값을 전달해야합니다. 다음은 수정 코드입니다.

var http = require('http'); 
var redis = require("redis"); 
var me = this; 
http.createServer(function (req, res) { 

    var x = null; 
    var key = "key"; 
    var redisClient = redis.createClient(); 

    me.foo(key, redisClient, function(err, result) { 
     x = result; 
     if(x == null) 
     { 
     // report error and quit 
       console.log('x is null'); 
       // write error message and status in HTTP response 
     } 
     // proceed 
     console.log('Proceeding...'); 
     // do some stuff using the value returned by foo to var x 
     // ......... 
     // ......... 
     res.writeHead(200, {'Content-Type': 'text/plain'}); 
     res.end('Hello World\n'); 
    }); 

}).listen(1400, '127.0.0.1'); 
console.log('Server running at http://127.0.0.1:1400/'); 


function foo(key, redisClient, callback) 
{ 
    console.log('I am inside foo'); 
    redisClient.get(key, function(error, result) { 
    if(error) { 
     console.log('error:' + error); 
     callback (error); 
    } else { 
     console.log('About to return from foo with result:' + result); 
     callback(null, result); 
    } 
    } 
} 
관련 문제