在node.js中,我们能否在执行下一个语句之前强制函数调用完成并返回?
Can we force a function call to complete and return before proceeding to next statement in node.js?
这里我有一个简单的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);
}
}
}
相关文章:
- 如何记录调用另一个函数的函数的返回值
- 从JSP页面调用Java Script函数未返回值
- 我可以获得用Ajax调用的函数的返回代码吗
- 从函数返回函数而不调用返回的函数
- jQuery deferred:用于延迟函数的返回,直到函数内的异步调用完成+获取返回值
- PHP调用脚本函数,返回值为Uncaught SyntaxError:意外的令牌ILLEGAL
- node.js for循环在函数调用返回之前进行迭代,从而产生对象问题
- 如何使用一些变量参数从javascript函数调用 asp.net C#函数并从C#函数获取字符串返回
- ajax 调用返回时可以向页面添加新的 javascript 函数吗?
- 使用 ajax 调用返回嵌套函数的值时出现问题
- 从 Javascript 调用 PHP 函数并返回一个数组
- JavaScript - 使用具有 AJAX 调用的函数的返回参数
- .done() 函数在抓取本地 JSON 文件时未在 AJAX 调用返回的承诺上运行
- javascript函数调用返回未定义和页面连续加载
- 分配给变量的javascript函数调用返回未定义的结果
- 递归函数调用返回
- 从函数调用返回对象的函数输出未定义
- 为什么这个函数调用返回一个字符串而不是一个数字
- 从嵌套异步函数调用返回谓词
- 如何在函数内部分配函数调用返回的值[JS]