JavaScript 中处理重复主键的模式

Pattern to handle duplicate primary keys in JavaScript

我正在使用 npm sequelize 库来存储 MySQL。主键是任务 ID,使用 shortid 库生成。

什么是好的 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。如果这些假设中的任何一个不成立,您 "may" 就会陷入循环,在这种情况下,您将不得不执行这些检查并有条件地中断递归。