gpt4 book ai didi

javascript - 我们可以强制函数调用完成并返回,然后再继续执行 node.js 中的下一条语句吗?

转载 作者:可可西里 更新时间:2023-11-01 11:21:56 25 4
gpt4 key购买 nike

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

I am inside foo

然后马上去汇报

x is null

此时异步redis.get调用结束,现在我明白了

About to return from foo with result: 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() 的返回。您需要在回调中将值传回。这是修改代码:

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

关于javascript - 我们可以强制函数调用完成并返回,然后再继续执行 node.js 中的下一条语句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24374645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com