2017-03-01 43 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