在JavaScript中处理重复主键的模式

Pattern to handle duplicate primary keys in JavaScript

本文关键字:模式 JavaScript 处理      更新时间:2023-09-26

我正在使用npm序列化库与MySQL存储。主键是使用shortid库生成的任务id。

什么是一个好的Javascript模式来处理重复的id,在不太可能的情况下,shortid给了我一个重复的键?我正在考虑在捕获重复键错误时返回false,并有一个外部while循环来重新尝试任务创建(使用新生成的id)。

这是一个相当丑陋的解决方案,那么有更好的方法来做到这一点吗?

        Task.create({
            id: shortid.generate(),
            content: task.content,
            deadline: task.deadline
        }).catch(function(error) {
            console.log('repeated id');
            return false;
        }).then(function() {
            console.log('yay ok');
            return true;
        });

你做对了。解决这个问题的唯一方法是,如果旧ID重复,则实际生成新ID。要在代码中表示这一点,您可以将create更改为递归函数,如下所示:

function createTask(task){
  Task.create({
            id: shortid.generate(),
            content: task.content,
            deadline: task.deadline
        }).catch(function(error) {
            console.log('repeated id');
            createTask(task);  // this will keep calling itself until it successfully creates the record with unique id
            return false;
        }).then(function() {
            console.log('yay ok');
            return true;
        });
}
// now creating the task will look like: 
createTask(task);

这肯定是一个乐观递归函数,假设您得到的唯一错误来自重复的ID,并且您的生成器最终将生成唯一的ID。如果这些假设中的任何一个为假,您"可能"陷入循环,在这种情况下,您将不得不实现这些检查并有条件地中断递归。