异步等待不等待

时间:2019-07-16 11:36:55

标签: javascript typescript promise es6-promise

我在Typescript中有以下内容:

import sql = require("mssql");
const config: sql.config = {....
}

const connect = async() => {
    return new Promise((resolve, reject) => {
        new sql.ConnectionPool(config).connect((err) => {
            if (err) {
                reject(err);
            } else {
                console.log("CONNECTED");
                resolve();
            }
        });
    });
};

(async() => {
    await connect().then(
        () => {
            console.log("Connection pool created successfully.");
        }).catch((err) => {
        console.error(err);
    });
})();

console.log("Now proceeding to load...");

我总是按照以下顺序获得控制台输出:

Now proceeding to load...
CONNECTED
Connection pool created successfully

我做错了什么?仅在完成所有活动之后才能执行最后一行代码?

3 个答案:

答案 0 :(得分:4)

您正在调用(async () => {...函数,它是异步的,然后直接继续打印加载消息。

您还将混合并匹配.then().catch()async/await/catch错误处理–我将重构如下内容:

import sql = require("mssql");

const connect: (config: sql.config) => Promise<sql.ConnectionPool> = async config =>
  new Promise((resolve, reject) => {
    const pool = new sql.ConnectionPool(config);
    pool.connect(err => {
      if (err) return reject(err);
      console.log("CONNECTED");
      resolve(pool);
    });
  });

const config: sql.config = {
  /*...*/
};

(async () => {
  console.log("Now proceeding to load...");
  try {
    const pool = await connect(config);
    console.log("Connection pool created successfully.");
  } catch (e) {
    console.error(e);
    return;
  }
})();

答案 1 :(得分:2)

尝试一下:

(async () => {
   await connect();
   console.log("Connection pool created successfully.");
})();

答案 2 :(得分:0)

尝试以下类似方法

import sql = require("mssql");
const config: sql.config = { /*....*/ };

const connect = () => {
    return new Promise((resolve, reject) => {
            try {
                let Connection = await sql.ConnectionPool(config).connect();
                console.log("Connected to mssql");
                resolve("Successfully Connected");
            } catch (error) {
                reject(error);
            }
    });
};

(async function () {
    try {
        let Connection = await connect();
        console.log("Connection pool created successfully.");
    } catch (error) {
        console.error(error);
    }
}());