【发布时间】:2017-10-04 22:44:36
【问题描述】:
我试图弄清楚如何让多个连续的等待调用按顺序发生。这是我的设置:
- 打字稿 2.5.2
- 转译为 es5
- 在 tsconfig 中使用库
es2017和dom
- 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