Bruno
Bruno

Reputation: 904

Multiple asynchronous function calls

given the situation there is an action inside a NodeJs server (in my case SailsJs) where I need to create x different entities in one call. It is not possible for the client to call the action x times. What is the best/recommended way of creating these entities regarding callbacks. If I understood callbacks right it is not possibile to just built something like this:

for(var i = 0; i < x; i++){
  User.create(...).exec(...);
}

What would be the right way to implement this?

Bruno

Upvotes: 0

Views: 57

Answers (2)

Manuel Reil
Manuel Reil

Reputation: 508

You can hand over an array of to be created users to User.create. You prepare the array of users first.

With lots of users to be created having some many-to-many relationships, native calls are much faster, e.g. Mongo bulk inserts.

Sails Reference regarding create

Upvotes: 1

KibGzr
KibGzr

Reputation: 2093

Easy do it with async package

var async = require('async');
async.times(x, function(n, next){
    User.create(...).exec(function(err, user) {
      next(err, user)
    })
}, function(err, users) {
  // processed x times 
});

Upvotes: 2

Related Questions