Jontsu
Jontsu

Reputation: 63

external function call, promise, async and Mongo - confused

Beginning to feel really thick here. Read a lot and I believe I understand promises and async-await decently well. However, I seem to struggle to use the function elsewhere, such that I can obtain the result (e.g. i get pending in another js file with: let dbConnection = dbOperations.openDatabaseConnection();).

Could someone explain to me why do I keep getting pending from the below functions (same function written with promise and asyncawait)? I can console.log the dbConnection result as expected prior to my return within the function. Also, I am particularly keen to understand promises in this sense, as it seems that many npm packages seem to return promises (and with my experience at least the async-await does not sit well with that? -> using async does not wait for resolve in my experience).

// Establish database connection

function openDatabaseConnection() {

    let dbConnection = {};

    return mongodb.connect(dbUri).then(conn => {
        dbConnection.connection = conn;
        return dbConnection;
    })
    .then(() => {
        dbConnection.session = dbConnection.connection.db(dbName);
        //console.log(dbConnection);
        return dbConnection;
    })
    .catch(err => {
        throw err;
    });
};

// Establish database connection

async function openDatabaseConnection() {

    let dbConnection = {};

    try {
        dbConnection.connection = await mongodb.connect(dbUri);
        dbConnection.session = await dbConnection.connection.db(dbName);
    } finally {
        //console.log(dbConnection);
        return dbConnection;
    };
};

Upvotes: 1

Views: 429

Answers (2)

David Lemon
David Lemon

Reputation: 1570

Async/await is just another way to work with Promises, just don't wait for something that isn't a Promise.

async function openDatabaseConnection() {

  let dbConnection = {};

  try {
    dbConnection.connection = await mongodb.connect(dbUri);
    // await here does not make sense, this function does not return a Promise
    // dbConnection.session = await dbConnection.connection.db(dbName);
    dbConnection.session = dbConnection.connection.db(dbName);
  } finally {
    //console.log(dbConnection);
    // return will always execute, keep here only when it should
    // return an empty object if the connection fails
    return dbConnection;
  };
};

More info on async/await

Upvotes: 0

Kristianmitk
Kristianmitk

Reputation: 4778

Both functions return again a promise.

So in your statement let dbConnection = dbOperations.openDatabaseConnection(); you assign a promise.

Thus you need to do something like:

dbOperations.openDatabaseConnection().then((dbConn) => ..)

or

let dbConnection = await dbOperations.openDatabaseConnection(); 

(note this requires to be wrapped in an async function)

Upvotes: 1

Related Questions