JavaCake JavaCake -4 years ago 125
Node.js Question

How to synchronously find instance and create in LoopBack

I am quite new with NodeJS and it is obviously causing some problems as things have a very asynchronously nature.

I am trying to find to instances which has to be used to create a new one (relation):

countryId
and
clientId
.

Obviously things are happening asynchronously so the variables are undefined. How do i make it synchronously?

This is my boot script in LoopBack

module.exports = function(app) {
var Client = app.models.Client
var Country = app.models.Country
var BillingAddress = app.models.BillingAddress

Client.create([
{username: 'test@test.gov', email: 'test@test.gov', password: 'nasapassword'},
{username: 'test2@test2.gov', email: 'test2@test2.gov', password: 'nanapassword'}
], function(err, clients){
if(err) throw err
})


Country.findOne({where: {name: 'Spain'}},
function(err, country) {
if(err) throw err
}
)

Client.findOne({where: {email: 'john@nasa.gov'}},
function(err, client) {
if(err) throw err
}
)

BillingAddress.create([
{first_name: 'Jimbo', last_name: 'Juice', address_line_1: 'Loool street', postal_code: '23232', countryId: country.id, clientId: client.id}
], function(err, billingaddress) {
if(err) throw err

})
}

Answer Source

It is not possible. The async function should be treated as an async call.

You can use async module.

module.exports = function(app, cb) {
    var Client = app.models.Client;
    var Country = app.models.Country;
    var BillingAddress = app.models.BillingAddress;

var clientData = [{username: 'test@test.gov', email: 'test@test.gov', password: 'nasapassword'},
        {username: 'test2@test2.gov', email: 'test2@test2.gov', password: 'nanapassword'}];

async.parallel({
  clients: function(callback){
    async.map(clientData, Client.create.bind(Client), function(err, clients){
      if(err) return callback(err);
      callback(null, clients);
    });    
  },
  country: function(callback){
    Country.findOne({where: {name: 'Spain'}}, callback);
  },
  nasaClient: function(callback){
    Client.findOne({where: {email: 'john@nasa.gov'}}, callback);
  }
}, function(err, results){
     if(err) return cb(err);

   BillingAddress.create([
        {first_name: 'Jimbo', last_name: 'Juice', address_line_1: 'Loool street', postal_code: '23232', countryId: results.country.id, clientId: results.nasaClient.id}
    ], function(err, billingaddress) {
        if(err) return cb(err);
        cb(null);
    });
});

}

Some points :

  • The boot script should be async too
  • Avoid throwing exceptions. Just handle it by callbacks
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download