首页 > 解决方案 > 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;
    };
};

标签: javascriptmongodbpromiseasync-await

解决方案


这两个函数都再次返回一个承诺。

因此,在您的声明中let dbConnection = dbOperations.openDatabaseConnection(); ,您指定了一个承诺。

因此,您需要执行以下操作:

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

或者

let dbConnection = await dbOperations.openDatabaseConnection(); 

(注意这需要包装在一个async函数中)


推荐阅读