简体   繁体   中英

Sailsjs create objects - nested creations

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM