Typescript - async、await 和 promise 不等待

Typescript - async, await and promise are not waiting

我正在尝试连接到 Snowflake DB,但程序没有等待连接函数完成,尽管我使用的是异步等待,但它仍在继续。

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.

感谢帮助!

承诺应解析为 conn,您可以通过传递给 connection.connect 的回调访问该 conn

// Doesn't have to be explicitly marked `async`, if you're not using `await` inside.
function createConnection() {
    return new Promise<any>((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.log(`Unable to connect: ${err.message}`);
                }
                else {
                    console.log('Successfully connected to Snowflake.');
                }

                // `conn` could be undefined, but your main function seems to handle that check...
                resolve(conn);
            }
        );
    });
}

async function main() {
    const connection = await createConnection();
    if (connection == undefined || !connection?.isUp()) {
        console.error('Failed to connect to snowflake...');
        return;
    }
}