【问题标题】:Typescript - async, await and promise are not waiting打字稿 - 异步,等待和承诺不等待
【发布时间】: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); - 此语句应该在 inside else 块内,该块在 connection.connect(..) 的回调函数内

标签: typescript async-await promise


【解决方案1】:

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

// 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;
    }
}

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 1970-01-01
    • 2018-02-03
    • 2018-03-05
    • 1970-01-01
    • 2021-11-09
    • 2022-01-22
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多