用nodejs,expressjs和sequelizejs开发一个宁静的应用程序,我发现我的代码做了很多回调。

特别是当我处理关联并在db中创建对象时,如下所示:

// db is my database object

// here are my db entities : header, line and thing
// header has many   line
// line   belongs to header
// line   has one    thing
// thing  has many   line

db.line.create().success(function(line){
  db.header.find({where:{id : header_id}}).success(function(header){
    header.addLine(line).success(function(){
      db.thing.find({where:{id : thing_id}}).success(function(thing){
        line.setThing(thing).success(function(){
          // OK
        });
      });
    });
  });
});


我想在错误回调中使用return语句,但无法获取创建的数据。

您是否认为还有另一种方法可以在没有所有回调的情况下进行此类操作?

最佳答案

在前面的示例中,这就是我创建和关联示例中的promises的样子:

// db is my database object

// here are my db entities : header, line and thing
// header has many   line
// line   belongs to header
// line   has one    thing
// thing  has many   line

db.line.create().success(function(line){
  db.header.find({where:{id : header_id}
  }).then(function(header){
    header.addLine(line);
  }).then(function(){
    return db.thing.find({where:{id : thing_id}
  }).then(function(thing){
    line.setThing(thing);
  }).then(function(){
    // OK
  }).catch(function(err){
    // handle errors of association
  });
.error(function(err){
   // handle errors of creation
});

07-26 09:35
查看更多