我正在MEAN堆栈上开发一个短暂的加密聊天室,我想知道如何最好地构建这段代码......
我想要实现的目标:
我有这个代码显然无法正常工作,因为对数据库的调用是异步的,会导致线程崩溃。
var chatroom = new Chatroom();
var roomid = random.generate(8).toUpperCase();
var unique = false;
while (!unique) {
Chatroom.count({roomid: roomid}, function (error, data) {
if (data < 1) {
chatroom.roomid = roomid;
chatroom.roomtitle = request.body.roomtitle;
chatroom.passphrase = request.body.passphrase;
unique = true;
}
});
}
chatroom.save(function (error) {
if (error) {
response.json(apiResponse('fail', error));
}
else {
response.json(apiResponse('success', chatroom));
}
});
有关如何更好地构建此代码的任何建议吗?
答案 0 :(得分:1)
我对MongoDB有点生疏,但也许这可能会有所帮助:
var chatroom = new Chatroom();
function generate() {
var roomid = random.generate(8).toUpperCase();
Chatroom.find({roomid: roomid}, function (error, data) {
if (data.length) {
chatroom.roomid = roomid;
chatroom.roomtitle = request.body.roomtitle;
chatroom.passphrase = request.body.passphrase;
save();
}
else {
generate();
}
});
}
function save () {
chatroom.save(function (error) {
if (error) {
response.json(apiResponse('fail', error));
}
else {
response.json(apiResponse('success', chatroom));
}
});
}
我经常发现递归是实现迭代的更好方法 - 至少更直观。