node-redis异步问题 - CNode技术社区

node-redis异步问题
发布于 10 年前 作者 Tei320 5537 次浏览 最后一次编辑是 9 年前 来自 问答

app.js

var express = require('express');
var redis = require('./models/redis.js');
var bodyParser = require('body-parser');
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// 扔一个漂流瓶
// POST owner=xxx&type=xxx&content=xxx[&time=xxx]
app.post('/', function(req, res) {
 console.log(req.body);
 if (!(req.body.owner && req.body.type && req.body.content)) {
 return res.json({code: 0, msg: "信息不完整"});
 }
 redis.throw(req.body, function(result) {
 res.json(result);
 console.log(result);
 });
});

redis.js

var redis = require('redis'),
 client = redis.createClient();
// 扔一个漂流瓶
exports.throw = function(bottle, callback) {
 bottle.time = bottle.time || Date.now();
 // 只是用为测试,最好基于时间和用户保证唯一
 var bottleId = Math.random().toString(16);
 var type = {male: 0, female: 1};
 // 根据漂流瓶类型的不同将漂流瓶保存到不同的数据库
 client.SELECT(type[bottle.type], function() {
 // 以 hash 类型保存漂流瓶对象
 client.HMSET(bottleId, bottle, function(err, result) {
 if (err) {
 return callback({code: 0, msg: "过会再试试吧"});
 }
 // 返回结果, 成功时返回 OK
 callback({code: 1, msg: result});
 // 设置漂流瓶生存期为 1 天
 client.EXPIRE(bottleId, 86400);
 });
 });
}

测试:

var request = require('request');
for (var i=1; i<=5; i++) {
 (function(i) {
 request.post({
 url: "http://127.0.0.1:3000",
 json: { owner: "bottle" + i, type: "male", content: "content" + i}
 });
 })(i);
}
for (var i=6; i<=10; i++) {
 (function(i) {
 request.post({
 url: "http://127.0.0.1:3000",
 json: { owner: "bottle" + i, type: "female", content: "content" + i}
 });
 })(i);
}
console.log("yes");

1 **问题:**源程序想根据性别将数据分别放在redis0,1库,结果都存放在1号库。 2 分析原因:本人新手,感觉是异步问题导致,就是进行HMSET时,因为异步数据库已经切换。但是不知道怎么办~ 3 求具体解决方法~大家帮忙~谢谢大家

3 回复

已解决,原因估计与node内部代码执行顺序有关~

client.SELECT(type[bottle.type], function() {});
 client.HMSET(bottleId, bottle, function(err, result) {
 if (err) {
 return callback({code: 0, msg: "过会再试试吧"});
 }
 // 返回结果, 成功时返回 OK
 callback({code: 1, msg: result});
 // 设置漂流瓶生存期为 1 天
 client.EXPIRE(bottleId, 86400);
 });

我们都已经ioredis了

回到顶部

AltStyle によって変換されたページ (->オリジナル) /