【发布时间】:2019-01-08 18:10:43
【问题描述】:
我正在使用 node-oracledb 连接到 Oracle 数据库。 API 提供了自己的 Promise,可以转换为 Promise<T>,因此“转换”为 Observable<T>。
使用 Observables,我想:
- 打开数据库连接
- 选择 N 条记录
- 关闭数据库连接,即使 #2 抛出异常。
使用传统的、阻塞的、程序化的方式,它会是这样的:
try
{
connection = Oracle.getConnection(...);
resultSet = connection.execute("SELECT ... FROM ...");
}
catch (Exception)
{
resultSet = EMPTY_RESULT;
}
finally
{
if (connection)
connection.close();
}
我尝试使用 Observables 编写此代码导致大量代码和回调。
受保护的方法 getConnection() 还是很简单的:
import * as Oracle from "oracledb";
protected getConnection() : Observable<IConnection>
{
return OraUtil.from(Oracle.getConnection(this.parameters));
}
closeConnection() 方法也是如此。我在这里直接使用了 Promise,以避免更多的代码。
protected closeConnection(subscriber : Subscriber<IExecuteReturn>, connection : IConnection) : void
{
connection.close()
.then(() => subscriber.complete())
.catch((error) => subscriber.error());
}
但是execute() 方法是麻烦开始的地方。
protected _execute(connection : IConnection, statement : string) : Observable<IExecuteReturn>
{
return new Observable<IExecuteReturn>(
(subscriber) => {
OraUtil.from(connection.execute(statement)).subscribe(
(result) => subscriber.next(result),
(error) => {
subscriber.error(error);
this.closeConnection(subscriber, connection);
},
() => {
this.closeConnection(subscriber, connection);
});
});
}
public execute(statement : string) : Observable<IExecuteReturn>
{
return this.getConnection().pipe(
flatMap((connection) => this._execute(connection, statement))
);
}
【问题讨论】:
标签: node.js typescript rxjs observable reactivex