Sequelize association - 请使用promise-style代替

时间:2014-11-08 12:19:57

标签: javascript node.js orm sequelize.js

我尝试将3个表加在一起ProductsSuppliersCategories,然后使用SupplierID = 13获取行。我已阅读How to implement many to many association in sequelize,其中介绍了如何关联0:M

数据库模型: enter image description here

代码:

var Sequelize = require('sequelize')
var sequelize = new Sequelize('northwind', 'nodejs', 'nodejs', {dialect: 'mysql',})
var Project = require('sequelize-import')(__dirname + '/models', sequelize, { exclude: ['index.js'] });

Project.Suppliers.hasMany(Project.Products, {foreignKey: 'SupplierID'});
Project.Products.belongsTo(Project.Suppliers, {foreignKey: 'SupplierID'});
Project.Categories.hasMany(Project.Products, {foreignKey: 'CategoryID'});
Project.Products.belongsTo(Project.Categories, {foreignKey: 'CategoryID'});

Project.Products
    .find({
        where: {
            SupplierID: 13
        },
        include: [
            Project.Suppliers,
            Project.Category,
        ]
    })
    .success(function(qr){
        if (qr == null) throw "Err";

        console.log("---");
        console.log(qr);
    })
    .error(function(err){
        console.log("Err");
    });

日志:

    EventEmitter#success|ok is deprecated, please use promise-style instead.
    EventEmitter#failure|fail|error is deprecated, please use promise-style instead.
    Err

2 个答案:

答案 0 :(得分:33)

更新:1月15日15日 - 添加了.finally()处理程序。还指出了.then()如何使用前一个处理程序中的参数以及如何执行下一个有序查询。

不推荐使用.success.error.done处理程序。错误并不重要,可能会在它们上保持向后兼容性。但你仍然应该改变它。

根据承诺A规格:http://wiki.commonjs.org/wiki/Promises/A

您现在应该执行以下样式:

db.Model.find(something)
  .then(function(results) {
      //do something with results
      //you can also take the results to make another query and return the promise.
      return db.anotherModel.find(results[0].anotherModelId);          
  }).then(function(results) {
      //do something else
  }).catch(function(err) {
      console.log(err);
  }).finally(function() {
        // finally gets called always regardless of 
        // whether the promises resolved with or without errors.
        // however this handler does receive any arguments.
  });

简而言之:

使用.then代替.success

使用.catch代替.error

使用.finally代替.done *注意:.finally无论如何都会被调用。

答案 1 :(得分:1)

我遇到了同样的问题,您可以使用单个.success更改.error.done(function(err, result))来执行这两项操作,并且警告消息也会消失。