0

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.

1 Answer 1

2

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;
            }
        });
    }
Sign up to request clarification or add additional context in comments.

2 Comments

He may not need async in front of (error) => { anymore.
True, and depending on how connect is written it may not even need the error callback at all as it may already be rejected and then thrown by the awaited statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.