Javascript 在继续执行node.js中的下一个语句之前,是否可以强制完成并返回函数调用?

Javascript 在继续执行node.js中的下一个语句之前,是否可以强制完成并返回函数调用?,javascript,node.js,asynchronous,redis,synchronous,Javascript,Node.js,Asynchronous,Redis,Synchronous,这里我有一个简单的HTTP服务器。调用foo()时,它会根据键获取一个值。但事实证明,当调用foo(key,redisClient)时,它会打印 我在福里面 然后立即报告 x is null 此时异步redis.get调用已经结束,现在我明白了 即将从foo返回,结果为:1 这就是我所期望的价值。但现在我的错误检查已经结束,它已经在HTTP响应中写入了错误。在继续主服务器线程中的任何其他操作之前,我如何确保从foo()中实际获得一个正确的返回值以存储到x var http = require(

这里我有一个简单的HTTP服务器。调用
foo()
时,它会根据键获取一个值。但事实证明,当调用
foo(key,redisClient)
时,它会打印

我在福里面

然后立即报告

x is null
此时异步redis.get调用已经结束,现在我明白了

即将从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;
            }
    }
}
redisClient.get()的调用不会传递给foo()的Return。您需要在回调中传递回该值。以下是修订代码:

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