在node.js中,我们能否在执行下一个语句之前强制函数调用完成并返回?

Can we force a function call to complete and return before proceeding to next statement in node.js?

本文关键字:函数调用 返回 语句 js node 我们 执行 下一个      更新时间:2023-09-26

这里我有一个简单的HTTP服务器。当foo()被调用时,它根据key获取一个值。但是,当调用foo(key, redisClient)时,它输出

我在foo里面

然后马上接着报告

x is null

此时异步redis。get call结束了,现在我看到

即将从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()调用中的Return不会传递给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);
    }
  }
}