loopbackjs - Asynchronous call in operation hook "loaded" mangles the result -


i using loopback v3.0.0-alpha.2 , have created application 2 models , have done migration mysql database.

what trying use operation hook "loaded" inject more data 1 model model when data retrieved.

before implementing "loaded" hook, when simple call on endpoint first model, let's receive 2 rows this:

[     {         "id": 1,         "name": "some name"     },     {         "id": 2,         "name": "some other name"     } ] 

to inject data tried following:

mymodel.observe('loaded', function somefunction(ctx, next) {     var mysecondmodel = mymodel.app.models.mysecondmodel;      if (some_condition) {         mysecondmodel.findbyid(ctx.data.some_id).then(function (data) {             ctx.data.some_property = data.some_property;         }).catch(function (err) {             next(err);         });     } else {         next();     } }); 

so, under condition, want lookup data second model , inject 1 of properties original context. strangely, when run , "loaded" hook called (and condition true), result becomes mangled this:

[     {         "id": 2,         "name": "some other name"     },     {         "id": 2,         "name": "some other name",         "some_property": "some_value"     } ] 

as can see, data duplicated first row. looking "dao.js" "loopback-datasource-juggler" package, found "dataaccessobject.find" function in particular "allcb" function , "async.foreach" loop on result set. if notifications turned on, first calls "withnotify" method after "loaded" hook has been executed, calls "buildresult" method.

when debugging flow, following calls happen:

  1. withnotify (one first row)
  2. withnotify (one second row)
  3. buildresult (on first row)
  4. buildresult (on second row)

the problem here seems variable "d" local "async.foreach" call gets overwritten in second "withnotify" data of second row , used reference context data, first execution of "buildresult" work on second data set.

so, questions are:

  1. is there proper way enrich data after retrieving data source?
  2. if not, there way can resolve asynchronous problem?

any appreciated, tobias.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -