0

I have a function in nodejs, whose instructions must be executed sequentially. I've tried the native options (async and await) for node 8 and promises. I can not make him wait for FindOne results before returning.

module.existe = function(usr, pass) {

  (async() => {

    await coleccion.findOne(
      { usr: usr, pass: pass },
      (err, result) => {
        return (result == null)? false : true;
      }
    );

  })();
}

the query to mongo is fine, I can recover the document, but always after returning, so the validation does not work. what this function should do is check if a set {usr, key} already exists in the database

What can be?

don tato
  • 1
  • 1
  • coleccion.findOne is type (, >)->(undefined) and you can't await undefined. You need a function of type ()->() so you can await the result. You can use util.promisify to convert. so `coleccion.findOneAsync = promisify(coleccion.findOne); const result = await coleccion.findOneAsync({usr, pass});` – generalhenry Apr 28 '18 at 20:58
  • This is basically a dup of [How do I return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323). You cannot return it directly because the function will return BEFORE the result is available. So, you either return a promise or use a callback. One of those two mechanisms can be used to communicate back the result. Javascript will not "wait" for the async value before the function returns. Even `async` and `await` will NOT do that for you. – jfriend00 Apr 28 '18 at 21:25
  • thank you very much @jfriend00 the answer was in the link you quoted. There was no way to work because I had a conceptual error. instead of waiting for the return of the function I must wait for the callback. thank you very much! – don tato Apr 28 '18 at 22:10

1 Answers1

1

generalhenry has already answered in the comments

Just making them altogether:

const { promisify } = require('util');

module.existe = function (usr, pass) {
    const findOnePromise = promisify(coleccion.findOne);

    (async () => {
        const result = await findOnePromise({ usr: usr, pass: pass });
        return (result === null) ? false : true;
    })();
}

Docs: await - util.promisify

Salah
  • 79
  • 3
  • This doesn't solve anything. And, `findOne()` already has a promise interface so there's no reason to promisify it. See what this question has been marked a dup of. The issue is that you cannot make Javascript wait for an async value before the function returns. You just can't. So, you have to use either a callback or a promise and use those to communicate back the async result. Mongodb's `.findOne()` already has a promise interface - no need to create a new one. – jfriend00 Apr 28 '18 at 21:27