【发布时间】:2021-04-04 18:20:25
【问题描述】:
我正在尝试连接到 Snowflake DB,但程序没有等待连接函数完成,尽管我使用的是 async-await,但它仍在继续。
async function createConnection() {
try {
return new Promise<any>(async (resolve, reject) => {
// Create a Connection object that we can use later to connect.
const connection = snowflake.createConnection({
account: envs.account,
username: envs.user,
password: envs.password,
}
);
// Try to connect to Snowflake, and check whether the connection was successful.
connection.connect(
(err, conn) => {
if (err) {
console.error('Unable to connect: ' + err.message);
}
else {
console.log('Successfully connected to Snowflake.');
}
}
);
resolve(connection);
})
}
catch (e) {
console.error(e);
}
}
async function main() {
const connection = await createConnection();
if (connection == undefined || !connection?.isUp()) {
console.error('Failed to connect to snowflake...');
return;
}
我得到的结果是:
Failed to connect to snowflake...
Successfully connected to Snowflake.
感谢您的帮助!
【问题讨论】:
-
createConnection函数和 executor 函数(传递给 promise 构造函数的函数)不应该是异步的。见:common promise anti-patterns -
就您的问题而言,
resolve(connection);- 此语句应该在 insideelse块内,该块在connection.connect(..)的回调函数内
标签: typescript async-await promise