【问题标题】:sequelize - cannot read property catch of undefined续集 - 无法读取未定义的属性捕获
【发布时间】:2016-01-27 08:09:21
【问题描述】:

我在我的项目中使用 mysql 的 sequelize。当前的用例是关于使用带有一些默认角色的“roles_master”填充表。

函数 createDefaultRoles 实现检查:

  • 如果表中有行
  • 如果是,并且 force 为真,则删除现有行并插入新行
  • 如果表为空,直接插入新行

我的代码如下...

/**
 *  Creates a pre-defined set of roles
 *  If roles table exists and already contains data, 
 *  this function simply returns, without creating any roles.
 *  The list of roles is defined in the file "ecp_db_defaults.js"
 *
 *  @param force -- boolean flag to indicate whether to drop existng roles and recreate afresh
 **/
function createDefaultRoles(force, callback) {
  console.log("Executing createDefaultRoles...");
  db.Role.count().then(function(result) {
    if (result>0) {
      if (force) {
        console.log("Emptying the roles table...");
        db.Role.destroy({force:true, where: {}}).then(function() {
          db.Role.bulkCreate(dbConfig.roles).done(function() {
            console.log("1. Successfully created user roles.");
            if (callback) return callback(null); else return;
          }).catch(function(e){
            console.log("Error while creating roles...", e);
            if (callback) return callback(e);
          });
        }).catch(function(e) {
          console.error("Error while destroying roles table.", e);
          return (callback)?callback(e):e;
        });
      }
      //if (callback) return callback(null); else return; 
    } else {
      db.Role.bulkCreate(dbConfig.roles).done(function(){
        console.log("2. Successfully created user roles.");
        if (callback) return callback(null);
      })
    }
  }).catch(function(e){
    console.error("Error while querying roles table.", e);
    if (callback) return callback(e);
  });
}

问题在于,它只能部分工作。虽然它能够删除现有行并添加新行,但它也会抛出一个异常,该异常被捕获并打印如下..

  • 正在执行 createDefaultRoles...
  • 正在清空角色表... 销毁角色表时出错。 [TypeError: Cannot read property 'catch'of undefined]
    1. 已成功创建用户角色。

最后,函数失败了,因为上面的错误。我尝试正确匹配所有 .then() 和 .catch() 承诺。他们似乎很好。

非常感谢任何帮助解决这个问题。

【问题讨论】:

    标签: mysql sequelize.js bluebird


    【解决方案1】:

    我猜问题出在区块

    db.Role.bulkCreate(dbConfig.roles).done(function() {
                console.log("1. Successfully created user roles.");
                if (callback) return callback(null); else return;
              }).catch(function(e){
                console.log("Error while creating roles...", e);
                if (callback) return callback(e);
              });
    

    由于 .done() 返回未定义,因此您不能在其上附加“catch”。 如果您将 .done 替换为 .then 它应该可以按预期工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-23
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      • 2018-08-23
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多