1

I just want the function to return the result of a mongodb query, and I can't get it to not return a promise.

function findResult(sequence){
    return dbo.collection("counter").findOne({ name: sequence })
}

I've tried so many things like await, callbacks using .then etc. Examples would be really appreciated, can't find any up-to-date examples on how to do this.

Edit:

I'm using the result to auto increment.

function findResult(sequence) {
       return dbo.collection("counter")
           .findOne({ name: sequence })
           .then(function (res) {
               return res;
           })
           .catch(function (err) {
           });
   }

   let result = findResult('test');
   console.log(result)

And this still returns Promise { <pending> }

2
  • 1
    How are you calling the function? That's an important part of the question. Commented Jul 6, 2021 at 10:29
  • You will always get a promise, the DB query is async operation Commented Jul 6, 2021 at 10:51

2 Answers 2

3

As DB queries are asynchronous process you need handle it differently, following are the ways to handle asynchronous process.

1) async/await

async function findResult(sequence) {
  return await dbo.collection("counter").findOne({ name: sequence });
}

// Function call
try {
   let result = await findResult(sequence);
}
catch(err){
// handle error;
}

2) Callback

function findResult(sequence, cb) {
  dbo.collection("counter").findOne({ name: sequence }, (err, res) => {
    if (err) {
      cb(err)
    } else {
      cb(null, res);
    }
  });
}

// Function call
let result = findResult(sequence, (err, res) => {
  if (err) {
    // handle error;
  } else {
    // handle result;
  }
});

3) Promise

function findResult(sequence) {
  return dbo
    .collection("counter")
    .findOne({ name: sequence })
    .then(function (res) {
      return res;
    })
    .catch(function (err) {
      // handle error;
    });
}

// Function call
let result = await findResult(sequence);
Sign up to request clarification or add additional context in comments.

2 Comments

Tried your third method because the output format matches what I need but it still throws a promise error
Just put await keyword in front of function call while using promise. let result = await findResult(sequence);
0

As query returns promise so you have to use then when calling your function, you can try like this to fetch the result

function findResult(sequence){
  return new Promise((resolve, reject) => {
    dbo.collection("counter").findOne({ name: sequence }).then(result => {
      resolve(result);
    })
   .catch(err => reject(err));
  })
} 

findResult("sdfsd").then(res => {
   console.log(res)
});

Comments

Your Answer

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