Reputation: 8689
I have a controller which accepts an API call /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. I need to create TaskSet
and then TaskSetEvents
.
TaskSet
requires task to be created and TaskSetEvents
requires TaskSet
to be created. 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");
});
});
Upvotes: 1
Views: 322
Reputation: 13164
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.
For your code snippet async.waterfall()
is definite way to go. 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.
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.
Upvotes: 1
Reputation: 15018
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.
Upvotes: 1