u936293
u936293

Reputation: 16224

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?

Upvotes: 0

Views: 5699

Answers (3)

Ratan Uday Kumar
Ratan Uday Kumar

Reputation: 6482

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

Upvotes: 0

AKX
AKX

Reputation: 168861

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

Upvotes: 5

Viktor Antishov
Viktor Antishov

Reputation: 41

Try this:

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

Upvotes: 2

Related Questions