Zuk*_*ker 18 javascript node.js sails.js waterline
我正在使用Postgres的风帆0.9.16,我的问题是:使用当前API使用promises执行事务的最佳方法是什么?可能有比以下更好的东西:
Model.query('BEGIN TRANSACTION', function (err) {
if (err) {
next(err);
} else {
Model
.create(...)
.(function (value) {
return [value, RelatedModel.create(...).then(...)];
})
.fail(function (err) {
Model.query('ROLLBACK');
next(err);
})
.spread(function (...) {
Model.query('COMMIT')
next(...);
})
}
})
Run Code Online (Sandbox Code Playgroud)
感谢帮助!
acl*_*ve1 21
我目前正在使用这个确切的工作流程.要使用promises执行一个查询,请执行以下操作:
Model
.query(params)
.then(function(result){
//act on result
})
.catch(function(error){
//handle error
})
.done(function(){
//clean up
});
Run Code Online (Sandbox Code Playgroud)
要并行执行多个查询,请执行以下操作:
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
});
Run Code Online (Sandbox Code Playgroud)
如果您试图避免在代码中嵌套:
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
});
Run Code Online (Sandbox Code Playgroud)
注意:目前,水线使用Q作为承诺.在这里有一个拉水要求将水线从Q切换到蓝鸟:水线/蓝鸟
当我回答这个问题时,我还没有上大学的数据库课,所以我不知道交易是什么.我做了一些挖掘,蓝鸟允许你用promises做交易.唯一的问题是,这并不完全内置于风帆中,因为它是一些特殊用例.这是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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10548 次 |
| 最近记录: |