我有一个处理连接设置和池的数据库模块,以及一个依赖数据库模块执行查询的查询模块。我正在调整它们以使用Promises进行异步调用。到目前为止,I've adapted the query module - 现在我希望转换数据库模块。
问题在于:数据库模块应该由查询模块(当前依赖于回调)直接和隐式地使用。如何在两个模块的方法中使用promises而不将其变成一个曲折的小段落的迷宫?
这是我到目前为止所做的:
数据库模块
getConnection: function(callback) { //this should return a promise
this.pool.getConnection(function(error, connection){
callback(error, connection);
});
},
查询模块这应该then
承诺getConnection
,执行查询,然后拒绝/解析它的来电者
request: function(queryRequest) {
return new Promise(function(resolve, reject){
Database.getConnection(function(error, connection){
if(error) {
reject({error: error, queryRequest: queryRequest});
} else {
connection.query(queryRequest.sql, queryRequest.values, function(error, rows, fields){
if(error) {
reject({error: error, queryRequest: queryRequest});
} else {
resolve({rows: rows, fields: fields, queryRequest: queryRequest});
}
connection.release()
});
}
});
});
},
答案 0 :(得分:2)
返回一个承诺
getConnection
应该为[连接]
而不是,它应该使用disposer pattern代替,并调用connection.release()
本身:
function withConnection(callback) {
var pool = this.pool;
var conn = new Promise(function(resolve, reject) {
pool.getConnection(function(error, connection){
if (error)
reject(error);
else
resolve(connection);
});
});
return conn.then(function(connection) {
var res = conn.then(callback); // safe call
return res.then(fin); // `finally` shim
function fin() {
connection.release();
return res;
}
});
}
function request(queryRequest) {
return Database.withConnection(function(connection) {
return new Promise(function(resolve, reject) {
connection.query(queryRequest.sql, queryRequest.values, function(error, rows, fields) {
if (error)
reject(error);
else
resolve({rows: rows, fields: fields, queryRequest: queryRequest});
});
});
}).catch(function(error) {
error.queryRequest = queryRequest;
throw error;
});
}
答案 1 :(得分:-2)
数据库模块
getConnection: function() {
return new Promise(function(resolve, reject) {
this.pool.getConnection(function(error, connection){
if(error) {
reject(error);
} else {
resolve(connection);
}
});
});
},
查询模块
execute: function(queryRequest) {
var self = this;
this.queryRequest = queryRequest;
return new Promise(function(resolve, reject) {
self.resolve = resolve;
self.reject = reject;
var promise = Database.getConnection();
promise.then(self.result.bind(self), self.fault.bind(self));
});
},
result: function(connection) {
var self = this;
connection.query(this.queryRequest.sql, this.queryRequest.values, function(error, rows, fields) {
if (error) {
self.reject(error);
} else {
self.resolve({rows: rows, fields: fields, queryRequest: self.queryRequest});
}
connection.release();
});
},
fault: function(info) {
self.reject(info);
}