简体   繁体   中英

Async await does not wait

I have the following in 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...");

I always get the console output in the following order:

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

What have I done wrong? How do I achieve executing the last line of code only after all the activities before it have completed execution?

You're calling the (async () => {... function, which is, well, asynchronous, and then directly proceed to print the loading message.

You're also mixing and matching .then().catch() and async/await/catch error handling – I'd refactor things like this:

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;
  }
})();

Try this:

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

try something like below

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);
    }
}());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM