我试图找出如何让多个背对背的等待调用按顺序发生。这是我的设置:
-
typescript 2.5.2
-
传输到es5
-
使用LIB
es2017
dom
在tsconfig中
-
节点。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;
}
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()
-
线
-
undefined
在结果中
-
-
结果=wait conn.query(querystr,params);
-
线
返回结果。排;
有没有关于我做错了什么的指导?在使用async/await的正确方法上,我是否完全被误导了?