1
Node.js和redis看起來很熱,但我正在燒。我不能優雅地克服看起來像一個非常簡單的任務:我應該如何編寫簡單的順序GET?
給定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
塊中重複它們?
然後我嘗試這種風格查詢DB的:
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();
一些閱讀並經過一番思考,我的解釋是,代碼獲取到response.write
S中的異步的GET返回之前,然後響應被關閉,所以內部寫入從不發生。至少我從第一個例子中注意到SET可以很容易地調用,但是我不知道(它看起來並不重要),如果它們是按照這個順序實際設置的。
所以,也許我正在做一些不適合node和redis的東西。我必須缺少一些基本的和明顯的東西。我需要做些什麼來升級?
或者告訴我我要回去到phpMyAdmin :(
這是有用的,謝謝! – 2012-04-17 01:13:26