Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Q with Strongloop Loopback

Q is a "supporting module" of loopback. I'm not totally sure what that means, but I'm assuming that it at least means that is possible to use Q with loopback's Persistent Model functions, like find() or findOne(). I'd like to know how to properly setup something like the following:

app.models.Question.findOne({
    where: {name: "My Question"}
}, function (err, result) {
    throw err if err
}).then(function () {
    console.log("success")
})

I have installed Q in my project's directory using NPM, but so far as I can tell, app.models.Question.findOne() is still returning undefined, rather than a usable Q promise.

According to the loopback docs, using Q,

If a function cannot return a value or throw an exception without blocking, it can return a promise instead.

What do I need to do to get loopback to return a promise in this situation?

like image 496
Michael.Lumley Avatar asked Jun 27 '26 15:06

Michael.Lumley


1 Answers

LoopBack queries do not return promises at this point in time. Please post a feature request in the LoopBack repository to remind us (after reading https://github.com/strongloop/loopback/wiki/Issues of course). However, I do believe ES6 promises are on the roadmap.

That said, you can create your own promise and return that instead:

var deferred = Q.defer();
app.models.Question.findOne({
  where: {
    name: 'My Question'
  }
}, function(err, result) {
  if (err) return deferred.reject(err);
  deferred.resolve(result);
});
return deferred.promise;

NOTE I haven't tested this, but it should be something along those lines. See https://github.com/kriskowal/q#using-deferreds for more info.

like image 133
superkhau Avatar answered Jun 29 '26 11:06

superkhau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!