Sequelize association - 请使用promise-style代替

Mat*_*Mav 6 javascript orm node.js sequelize.js

我想加入3代表一起Products,SuppliersCategories再和同排SupplierID = 13.我已经阅读了如何在sequelize中实现多对多关联,并解释了如何关联0:M.

数据库模型: 在此输入图像描述

码:

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");
    });
Run Code Online (Sandbox Code Playgroud)

日志:

    EventEmitter#success|ok is deprecated, please use promise-style instead.
    EventEmitter#failure|fail|error is deprecated, please use promise-style instead.
    Err
Run Code Online (Sandbox Code Playgroud)

Cal*_*twr 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.
  });
Run Code Online (Sandbox Code Playgroud)

简而言之:

.then而不是.success

.catch而不是.error

使用.finally而不是.done *note:.finally总是会被调用.