我目前正在使用这个确切的工作流程。要使用 Promise 执行一个查询,请执行以下操作:
Model
.query(params)
.then(function(result){
//act on result
})
.catch(function(error){
//handle error
})
.done(function(){
//clean up
});
要并行执行多个查询,请执行以下操作:
var Promise = require('q');
Promise.all([
User.findOne(),
AnotherModel.findOne(),
AnotherModel2.find()
])
.spread(function(user,anotherModel,anotherModel2){
//use the results
})
.catch(function(){
//handle errors
})
.done(function(){
//clean up
});
如果您想避免在代码中嵌套:
Model
.query(params)
.then(function(result){//after query #1
//since you're returning a promise here, you can use .then after this
return Model.query();
})
.then(function(results){//after query#2
if(!results){
throw new Error("No results found in query #2");
}else{
return Model.differentQuery(results);
}
})
.then(function(results){
//do something with the results
})
.catch(function(err){
console.log(err);
})
.done(function(){
//cleanup
});
注意:目前,waterline 使用 Q 表示 promise。这里有一个将水线从 Q 切换到 bluebird 的拉取请求:waterline/bluebird
当我回答这个问题时,我还没有在大学上过数据库课,所以我不知道什么是事务。我做了一些挖掘工作,bluebird 允许您使用承诺进行交易。唯一的问题是,这并没有完全内置在风帆中,因为它是一个特殊的用例。这是 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;