0

I want the array length, but the function returns [object Promise]. I send a correct email and I just need know if it's already in collection.

 const res = require('express/lib/response');

 async function emailUnique(email){

    var query = { email: email }; 

    const response = await dbo.collection('users').find(query).toArray();

    const tot = response.length;

    return tot;

} 


const emailValidate = function (email) {

    if (email.indexOf('@') === -1 || email.indexOf('.') < 0) {
        message = 'Invalid entries. Try again.';
    }else{

        let quantos = emailUnique(email);

        message = quantos;

    }

    return message;
  
};

module.exports = emailValidate;
  • There's no way to return the value of an async function synchronously. If you really want your `emailValidate` function code to look synchronous then you can try making it async and using the `await` keyword to wait for the database response. – Abir Taheer Feb 11 '22 at 19:24
  • But I maked this , or I'm mistaked? const response = await dbo.collection('users').find(query).toArray(); – Luis Miguel Feb 11 '22 at 19:57
  • That's because the `emailUnique` function is `async`. You are allowed to use the `await` keyword only inside of another `async` function. You cannot await an asynchronous function from inside of a synchronous one. – Abir Taheer Feb 11 '22 at 19:59
  • If you are dead set on making the the database call synchronously then this answer might help: https://stackoverflow.com/questions/9121902/call-an-asynchronous-javascript-function-synchronously but it is far from ideal and defeats the whole benefit of being able to write async code in javascript. – Abir Taheer Feb 11 '22 at 20:01

1 Answers1

0

Thanks, Its a simplified answer:

emailValidate.mod.js

const res = require('express/lib/response');
     
function emailValidate(email) {
    return new Promise((resolve) => { // return a promise
        var query = { email: email };
        dbo.collection('users').find(query).toArray((_err, result) => {
            resolve(result.length); //the returned value 
        });       
    });      
}
     
module.exports = emailValidate;

user.js

const mod_emailValidate = require('./emailValidate.mod');
     
exports.getUsers = (req, res) => {
    const { name } = req.body;
    const { email } = req.body;
    const { password } = req.body;
     
    async function run() { // make an async function
        let data = await mod_emailValidate(email); //call the function with await                  
        console.log(`Retornou: ${data}`); 
    }
     
    run();  
     
    res.status(400).send({ message: 'Fired' });     
};


 
Tyler2P
  • 2,324
  • 26
  • 22
  • 31