【问题标题】:Typescript multiple sequential awaits not blocking打字稿多个顺序等待不阻塞
【发布时间】:2017-10-04 22:44:36
【问题描述】:

我试图弄清楚如何让多个连续的等待调用按顺序发生。这是我的设置:

  • 打字稿 2.5.2
    • 转译为 es5
    • 在 tsconfig 中使用库 es2017dom
  • node.js 8.6
  • 部署到在 minikube 0.22.2 中运行的 docker 容器

这是问题代码。它正在使用 node pg 包对 postgresql 运行查询。我基于示例代码https://node-postgres.com/features/transactions#a-pooled-client-with-async-await

import { Client, Pool } from 'pg';

// An existing client connection can be passed in so that the calling code
// can manage a transaction. If none is provided, a new connection is
// retrieved from the connection pool.
async function query(
  connPool: Pool,
  querystr: string,
  params: (number | string)[],
  client?: Client
): Promise<any[]> {
  let result;
  let conn: Client = client;
  if (conn) {
    result = await conn.query(querystr, params);
  }
  else {
    conn = await connPool.connect();
    result = await conn.query(querystr, params);
    conn.release();
  }
  return result.rows;
}

我正在从另一个文件中调用 query() 函数,如下所示:

const results = await query(myPool, 'SELECT * FROM my_table');
doOtherThing(results);

根据我见过的每个源代码示例,我希望它的行为方式如下:

  • 对 query() 的调用
  • conn = await connPool.connect(); 行会阻塞,直到从池中检索到连接
  • result = await conn.query(querystr, params); 行会阻塞,直到检索到查询结果
  • return result.rows; 行将结果返回给调用代码
  • 调用代码从数据库中接收记录
  • doOtherThing() 被调用

但是,它是按以下顺序执行的:

  • 对 query() 的调用
  • conn = await connPool.connect(); 行立即返回
  • 调用代码在结果中收到undefined
  • doOtherThing() 被调用
  • result = await conn.query(querystr, params); 行立即返回,无处可去
  • return result.rows; 行结果无处返回

关于我做错了什么的任何指导?我在使用 async/await 的正确方法上完全被误导了吗?

【问题讨论】:

  • 我的工作正常。你如何创建connPool?您使用的是什么版本的节点? tsconfig.json 中的 target 设置为什么?
  • @Wainage:我使用connPool = new Pool(settings) 创建连接池,其中 settings 是具有 postgres 连接配置的对象。使用节点 8.6。 tsconfig 中的目标是 es5。上面显示的 query() 代码是在我导入的单独包中实现的(我也写过),所以它位于我调用该函数的项目的 node_modules/ 中。
  • 为了清楚起见,我更新了代码示例,它更好地说明了正在发生的事情。我有一个语句 doOtherThing(results); 在调用 query() 之后发生。我写这篇文章是假设在 query() 函数中的所有异步等待函数都成功解决了它们的承诺之前不会调用该语句。

标签: node.js typescript async-await ecmascript-5


【解决方案1】:

我发现了问题。问题中列出的预期行为是正确的。

在语句const results = await query(myPool, 'SELECT * FROM my_table'); 和实际函数之间是另一个同名的函数query()。这个其他函数充当了我在原始帖子中包含的query() 函数的实现的传递。中间的这个函数没有返回任何东西,导致了意外的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多