【问题标题】:nodejs mssql transaction poolnodejs mssql 事务池
【发布时间】:2019-06-15 00:36:33
【问题描述】:

我有一个打字稿模块。

public multipleQuery(queries: string[]) {
    return new Promise(async (resolve, reject) => {
      const cPool = new sql.ConnectionPool(this.room.db);
      await cPool.connect().then((pool: any) => {
        const transaction = new sql.Transaction(pool);
        return transaction.begin(async (err: any) => {
          const request = new sql.Request(transaction, { stream: true });
          try {
            queries.forEach(async (q) => {
              await request.query(q);
            });
            transaction.commit((err2: any) => {
              pool.close();
              if (err2) {
                reject(err2);
              } else {
                resolve(true);
              }
            });
          } catch (err) {
            transaction.rollback(() => {
               pool.close();
               reject(err);
            });
          }
        });
      }).catch((err: Error) => {
        cPool.close();
        reject(err);
      });
    });
}

queries变量是一个字符串数组,我在里面放了很多sql插入查询。 不管我在查询中写什么,我仍然收到这个错误,为什么?

RequestError: 请求只能在 LoggedIn 状态下进行,不能在 SentClientRequest 状态 TransactionError:无法获取连接 请求。还有一个请求正在进行中。

【问题讨论】:

标签: node.js typescript promise


【解决方案1】:

解决方案是使用async

const async = require("async");

public multipleQuery(queries: string[]) {
return new Promise((resolve, reject) => {
  const pool = new sql.ConnectionPool(this.room.db);
  return pool.connect().then((p: any) => {
    const transaction = new sql.Transaction(p);
    return transaction.begin((err: any) => {
        const request = new sql.Request(transaction);
        if (err) {
          reject(err);
        }
        return async.eachSeries(queries, async (query: any, callback: any) => {
            return request.query(query);
          }, async (err2: any) => {
            if ( err2 ) {
              await transaction.rollback(() => {
                pool.close();
                reject(err2);
              });
            } else {
              await transaction.commit(() => {
                pool.close();
                resolve(true);
              });
            }
          });
      });
  });
});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多