Justin
Justin

Reputation: 45350

JavaScript using async/await from a class

I have a JavaScript class and I am trying to figure out how to use the new async/await keywords in the connect method.

module.exports = class {
    constructor(url) {
        if(_.isEmpty(url)) {
            throw `'url' must be set`;
        }

        this.url = url;
        this.client = new MongoClient(url, {
            useNewUrlParser: true
        });
    }

    connect() {
        this.client.connect(async (error) => {
            if(error) {
                throw error;
            }
        });
    }
};

Essentially I want wait until connect() returns from the callback. I added async in front of the callback, but don't I need an await statement as well? I am getting a UnhandledPromiseRejectionWarning from Node.js.

Upvotes: 0

Views: 352

Answers (1)

Alex Broadwin
Alex Broadwin

Reputation: 1338

If connect is an async function/returns a promise then you can await the call if you're calling it from within an async function, like so:

async connect() {
        await this.client.connect(async (error) => {
            if(error) {
                throw error;
            }
        });
    }

Upvotes: 2

Related Questions