How to use Model.query() with promises in SailsJS/Waterline?

YannP picture YannP · Feb 19, 2014 · Viewed 10.3k times · Source

I'm having issues with Sails.JS 0.9.8. I would like to use promises with the Model.query() function (I use sails-mysql adapter).

This code will work :

User.findOne({ email: email })
.then(function(user) {
  console.log(user);
});

but this one won't

User.query("SELECT email FROM user WHERE email = ?", [ email ]))
.then(function(err, rows) {
  console.log(rows);
})

I get undefined for both 'err' and 'rows'.

Is it just not implemented or I am doing something wrong ? If not implemented, is there any alternative to use promises with .query() ?

Thank you in advance

Answer

Steve Kehlet picture Steve Kehlet · Nov 6, 2014

You can promisify(User.query) yourself, just like you'd do for any other callback-based API, like:

var Promise = require('bluebird');

....

var userQueryAsync = Promise.promisify(User.query);
userQueryAsync("SELECT email FROM user WHERE email = ?", [ email ])
.then(function(user) {
    console.log(user);
});