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

烈酒焚心 提交于 2019-12-01 14:24:37

问题


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


回答1:


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);
});



回答2:


As a hack you can monkeypatch all your models in bootstrap like this

module.exports.bootstrap = function(cb) {
    var Promise = require('bluebird');

    Object.keys(sails.models).forEach(function (key) {
        if (sails.models[key].query) {
            sails.models[key].query = Promise.promisify(sails.models[key].query);
        }
    });

    cb();
};



回答3:


The query method is specific to sails-mysql, and doesn't support deferred objects the way that the more general Waterline adapter methods (e.g. findOne, find, create, etc) do. You'll have to supply a callback as the second argument.




回答4:


In case you do not want to use promisify but do want SailsModel.query to return a promise.

/**
 * @param {Model} model - an instance of a sails model
 * @param {string} sql - a sql string
 * @param {*[]} values - used to interpolate the string's ?
 *
 * @returns {Promise} which resolves to the succesfully queried strings
 */
function query(model, sql, values) {
  values = values || [];

  return new Promise((resolve, reject) => {

    model.query(sql, values, (err, results) => {
      if (err) {
        return reject(err);
      }

      resolve(results);
    });
  });
}

// and use it like this
query(User, 'SELECT * FROM user WHERE id = ?', [1]).then(console.log);


来源:https://stackoverflow.com/questions/21886630/how-to-use-model-query-with-promises-in-sailsjs-waterline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!