0

I am using bluebird and sails to build my application. When I use a database call inside the promise, it show me the warning like

Warning: a promise was created in a handler but was not returned from it

var P = require('bluebird');
return new P(function (resolve, reject) {
  Product.find({
    or: [
      {barcode: {'contains': q}},
      {name: {'contains': q}},
      {registrationCode: {'contains': q}}
    ]
  })
  .populate('batches')
  .exec(function (err, products) {
    if (err) return reject(err);
    return resolve(products);
  });
}); //- end promise
Dzanvu
  • 523
  • 7
  • 18
  • Doesn't Sails already return promises? If so, you should avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572). – Bergi Apr 11 '16 at 14:46

2 Answers2

0

//add return
return Product.find({
...
//wrapping inside bluebird promise wrapper is unnecessary here as well

...This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

Please refer to the documentation, standard

Yerken
  • 1,944
  • 1
  • 14
  • 18
0

Change your code to this:

return Product.find({
    or: [
      {barcode: {'contains': q}},
      {name: {'contains': q}},
      {registrationCode: {'contains': q}}
    ]
  })
  .populate('batches')
  .exec().then(function(products) {
      //  your processing here
  });

.exec() already creates a promise, so you can just return that promise without wrapping it in another promise.

The warning you saw was because you weren't doing anything with a promise that was created inside an existing promise handler. Without seeing more code, we can't say for sure if the warning was caused by you ignoring the promise that .exec() returns or if you aren't actually doing anything with the promise that this function returns.

See the Bluebird explanation for that warning here. That makes it sound likely that the issue is that you were ignoring the promise returned by .exec().

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • I have some processing in the exec(), and this function is a service, which will be called by other methods. So I should do something in the exec() – Dzanvu Apr 15 '16 at 08:01
  • @Dzanvu - `.exec()` returns a promise. If you're using promises, you can do the processing in a `.then()` handler added to the promise that is returned from `.exec()`. I added an example of that to the code in my answer. – jfriend00 Apr 15 '16 at 14:55
  • you mean that if this function is called `AService.f`, and '// your processing here' is replaced by `return {a: 1, b: 2}`, I can get the object of `{a: 1, b: 2}` in another model action called `AController.g` via `AService.f(paramsPassed).then(function (obj) { console.log(obj); })`? As a result, the console.log can print `{a: 1, b: 2}` – Dzanvu May 10 '16 at 13:53