Node.js和redis看起来很热,但我被烧了。我无法优雅地克服看似简单的任务:
给出3个数字,检查前两个是否大于10.如果是,请打印第三个数字。
我用这个相当滑稽的剧本完成了这项任务:
var http = require("http");
var redis = require("redis");
client = redis.createClient();
http.createServer(function(request, response) {
client.SET("key1", "11");
client.SET("key2", "9");
client.SET("key3", "3");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello\n\n");
client.GET("key1", function(err, reply) {
response.write(reply + "\n\n");
if(parseInt(reply) > 10) {
client.GET("key2", function(err, reply) {
response.write(reply + "\n\n");
if(parseInt(reply) > 10) {
client.GET("key3", function(err, reply) {
response.write(reply + "\n\n");
response.end();
client.end();
});
} else {
response.end();
client.end();
}
});
} else {
response.end();
client.end();
}
});
}).listen(8000);
我注意到的一些事情是:
response.end()
需要在某处显示write
s才能显示。如何避免在else
块中重复它们?然后我尝试了这种查询数据库的方式:
http.createServer(function(request, response) {
client.SET("key1", "11");
client.SET("key2", "9");
client.SET("key3", "3");
var key1 = 0;
var key2 = 0;
var key3 = 0;
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello\n\n");
client.GET("key1", function(err, reply) {
response.write(reply + "\n\n");
key1 = parseInt(reply);
});
client.GET("key2", function(err, reply) {
response.write(reply + "\n\n");
key2 = parseInt(reply);
});
client.GET("key3", function(err, reply) {
response.write(reply + "\n\n");
key3 = parseInt(reply);
});
response.write(key1 + "\n\n");
response.write(key2 + "\n\n");
response.write(key3 + "\n\n");
response.end();
client.end();
经过一些阅读和思考之后,我的解释是代码在异步GET返回之前到达response.write
,然后响应被关闭,因此内部写入永远不会发生。至少我从第一个例子中注意到SET可以很容易地被调用,但我不知道(并且它似乎并不重要)它们是否按实际顺序设置。
所以,也许我正在做一些不适合节点和redis的事情。我必须遗漏一些基本而明显的东西。升级需要做什么?
或者告诉我,我必须回到PhpMyAdmin :(