[英]Sailsjs create objects - nested creations
I have a controller which accepts an API call /task/:id/start. 我有一个接受API调用/ task /:id / start的控制器。 My controller method needs to check if Task with at id is valid and if that's valid then I need to create 2 other model instances.
我的控制器方法需要检查ID为ID的Task是否有效,如果有效,那么我需要创建2个其他模型实例。 I need to create
TaskSet
and then TaskSetEvents
. 我需要先创建
TaskSet
,然后创建TaskSetEvents
。
TaskSet
requires task to be created and TaskSetEvents
requires TaskSet
to be created. TaskSet
要求创建任务和TaskSetEvents
需要TaskSet
创建。 Here is how I'm planning on creating these events. 这是我计划创建这些事件的方式。 I'm not sure if there is a better way of creating these objects.
我不确定是否有更好的方法来创建这些对象。
TaskSet.create({ task: task}).exec(function(err, taskSet) {
TaskSetEvent.create({ taskSet: taskSet, eventType: 'start'}).exec(function (err, taskSetEvent) {
console.log("Everything created ok");
});
});
This should just work: 这应该工作:
TaskSetEvent.create({
eventType: 'start',
taskSet: {
task: myTask
}
})
.then(function (taskSetEvent) {
console.log('should be done here');
});
If you're doing this through a controller endpoint, you shouldn't have to write any code. 如果通过控制器端点执行此操作,则不必编写任何代码。 Just
POST
your nested object. 只是
POST
的嵌套对象。
Everything is fine with your code. 您的代码一切都很好。 Anyway, when there are more nested functions code becomes hard to read and maintain, something called spaghetti code or callback hell.
无论如何,当有更多的嵌套函数代码变得难以阅读和维护时,这就是所谓的意大利面条式代码或回调地狱。
In JavaScript common ways of solving callback problem are using promises or using special tools, like async.js . 在JavaScript中,解决回调问题的常用方法是使用promise或使用特殊工具,例如async.js 。
For your code snippet async.waterfall()
is definite way to go. 对于您的代码段,
async.waterfall()
是必经之路。 You can rewrite it in such way: 您可以用以下方式重写它:
async.waterfall([
function(cb) {
TaskSet.create({ task: task}).exec(cb);
},
function(err, taskSet, cb) {
TaskSetEvent.create({ taskSet: taskSet, eventType: 'start'}).exec(cb);
}
], function(err, taskSetEvent) {
console.log('Everything created ok');
});
waterfall
method runs series of functions each passing the results to the next. waterfall
方法运行一系列函数,每个函数将结果传递给下一个函数。
Not worth saying that if you want to use async frequently, it is not necessary to require it each time in your modules, you can just install it via npm and save async: true
in your globals config. 不用说,如果您想频繁使用异步,则不必每次都在模块中要求它,只需通过npm进行安装并在全局配置中保存
async: true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.