我目前正在使用这个确切的工作流程。要使用promises执行一个查询,请执行以下操作:
Model
.query(params)
.then(function(result){
})
.catch(function(error){
})
.done(function(){
});
要并行执行多个查询,请执行以下操作:
var Promise = require('q');
Promise.all([
User.findOne(),
AnotherModel.findOne(),
AnotherModel2.find()
])
.spread(function(user,anotherModel,anotherModel2){
})
.catch(function(){
})
.done(function(){
});
如果您想避免在代码中嵌套:
Model
.query(params)
.then(function(result){
return Model.query();
})
.then(function(results){
if(!results){
throw new Error("No results found in query #2");
}else{
return Model.differentQuery(results);
}
})
.then(function(results){
})
.catch(function(err){
console.log(err);
})
.done(function(){
});
注意:目前,Waterline使用 Q 来处理 Promise。这里有一个拉取请求将 Waterline 从 Q 切换到 Bluebird:waterline/bluebird
当我回答这个问题时,我还没有上过大学的数据库课程,所以我不知道什么是事务。我查了一些资料,发现 Bluebird 可以让你使用 Promise 来处理事务。唯一的问题是,这不是 Sails 内置的功能,因为它是一种特殊的用例。以下是 Bluebird 在这种情况下提供的代码。
var pg = require('pg');
var Promise = require('bluebird');
Promise.promisifyAll(pg);
function getTransaction(connectionString) {
var close;
return pg.connectAsync(connectionString).spread(function(client, done) {
close = done;
return client.queryAsync('BEGIN').then(function () {
return client;
});
}).disposer(function(client, promise) {
if (promise.isFulfilled()) {
return client.queryAsync('COMMIT').then(closeClient);
} else {
return client.queryAsync('ROLLBACK').then(closeClient);
}
function closeClient() {
if (close) close(client);
}
});
}
exports.getTransaction = getTransaction;