2017-03-01 73 views
0

我对NodeJS非常新,它显然会导致一些问题,因为事情具有非同步性质。如何同步查找实例并在LoopBack中创建

我想找到必须用来创建一个新的(关系)的实例:countryIdclientId

显然事情是异步发生的,所以变量是未定义的。我如何使它同步?

这是回送

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

    Client.create([ 
     {username: '[email protected]', email: '[email protected]', password: 'nasapassword'}, 
     {username: '[email protected]', email: '[email protected]', 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: '[email protected]'}}, 
     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 

    }) 
} 

回答

1

我的启动脚本这是不可能的。异步函数应该被视为异步调用。

您可以使用async模块。

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

var clientData = [{username: '[email protected]', email: '[email protected]', password: 'nasapassword'}, 
     {username: '[email protected]', email: '[email protected]', 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: '[email protected]'}}, 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); 
    }); 
}); 

} 

几点:

  • 引导脚本应该是异步太
  • 避免抛出异常。仅仅通过callback小号
+0

处理它,所以我列入“异步”和我得到以下错误,当我运行的代码'类型错误:this.getDataSource不是function' – JavaCake

+0

@JavaCake在哪里使用''this.getDataSource ? –

+0

不通,它是我第一次看到这个.. – JavaCake