0

I tried to export my async function to another service from a service with this class and this function inside it.

It looks like this:


const express = require("express");
const mongoDB = require('mongodb').MongoClient;
const url = "here I paste url to my databse(everything is good here)";

class CheckService {

    async isUserExists(username) {
        const connection = await mongoDB.connect(url);
        const query = {name: username};
        const db = connection.db("users");
        const result = await db.collection("users").find(query).toArray();
        connection.close();
        return result.length !== 0;
    }

}

module.exports = new CheckService();

After this, in another service, I imported it like this:

const checkService = require('./check.service');

And I called my function like this:

console.log('function:', checkService.isUserExists(username));

After this, in the console, I have: function: Promise { pending }

What's wrong here? I don't very understand how promises, async, and await work. Can you give me something to read or watch about promises, async, await and other stuff like this? Please, help!

  • Btw, you shouldn't use `class` syntax if you don't make multiple instances. Just create an object literal. – Bergi Dec 31 '22 at 10:25

1 Answers1

0

you need to call the function with await keyword, like this:

await checkService.isUserExists(username);

or you can chain your promise like this

checkService.isUserExists(username)
    .then((promiseReturnValue) => { console.log(promiseReturnValue) })
    .catch((error) => { console.log(error); })

To catch an error using async await form you should use try catch block or (is not your case) check the result for a falsy value.

Example try catch block:

try {
  const returnValue = await checkService.isUserExtists();
  console.log(returnValue);
} catch (error){
  console.log(error)
}
CtrlSMDFK
  • 91
  • 1
  • 4