打字稿多个顺序等待不阻塞

时间:2017-10-04 22:44:36

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

我正在试图弄清楚如何以连续的顺序进行多次背靠背等待调用。这是我的设置:

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

这是问题代码。它正在使用节点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的正确方法?

1 个答案:

答案 0 :(得分:0)

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

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

相关问题