javascript 如何在 SailsJS/Waterline 中使用带有承诺的 Model.query()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21886630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Model.query() with promises in SailsJS/Waterline?
提问by YannP
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).
我在使用 Sails.JS 0.9.8 时遇到了问题。我想在 Model.query() 函数中使用 promise(我使用sails-mysql 适配器)。
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'.
我对 'err' 和 'rows' 都未定义。
Is it just not implemented or I am doing something wrong ? If not implemented, is there any alternative to use promises with .query() ?
它只是没有实施还是我做错了什么?如果没有实现,有没有其他方法可以使用 .query() 的承诺?
Thank you in advance
先感谢您
回答by Steve Kehlet
You can promisify(User.query)
yourself, just like you'd do for any other callback-based API, like:
您可以promisify(User.query)
自己,就像您对任何其他基于回调的 API 所做的一样,例如:
var Promise = require('bluebird');
....
....
var userQueryAsync = Promise.promisify(User.query);
userQueryAsync("SELECT email FROM user WHERE email = ?", [ email ])
.then(function(user) {
console.log(user);
});
回答by Chad Scira
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();
};
回答by sgress454
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.
该query
方法是特定于帆,MySQL和不支持推迟对象的方式,更一般的水线适配器的方法(例如findOne
,find
,create
等)做的。您必须提供回调作为第二个参数。
回答by bas080
In case you do not want to use promisify but do want SailsModel.query to return a promise.
如果您不想使用 promisify 但确实希望 SailsModel.query 返回一个承诺。
/**
* @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);