gpt4 book ai didi

javascript - Sequelize.js 创建太多回调

转载 作者:行者123 更新时间:2023-12-03 11:57:49 25 4
gpt4 key购买 nike

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

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

// 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语句,但我无法获取创建的数据。

您认为还有另一种方法可以在不使用所有回调的情况下执行此类操作吗?

最佳答案

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

// 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
});

关于javascript - Sequelize.js 创建太多回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25525467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com