Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

async await data return from backend node.js

I have this function:

module.exports = async function(username, password, mongo_uri, cluster, collection) {
    
    let client = new MongoClient(mongo_uri)
    let database = client.db(cluster)
    let collection_name = database.collection(collection)

    
    if (!username || !password || !username && !password) {
        return false
    } else {
        //query mongo
       MongoClient.connect(mongo_uri, async function(err, db) {
            if (err) {
                console.log(err);
            }
            collection_name.find({'email': username}).toArray(async function(e,doc){
                if(doc.length === 0) {
                    db.close();
                    return false
                } else {
                    db.close();
                    return true
                }
            });
        })
    }
 } 

and I have this in the front-end:

 let results = await mongo_login_api(username, password, mongo_uri, cluster, collection)
console.log("results")
console.log(results)

when I run this function, it doesn’t wait for the backend to return anything. How can I fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

My suggestion is:

You put all body of your funcion in Promise.

For example:

module.exports = function(username, password, mongo_uri, cluster, collection) {
    return new Promise((resolve, reject) => {
       let client = new MongoClient(mongo_uri)
       let database = client.db(cluster)
       let collection_name = database.collection(collection)

    
       if (!username || !password || !username && !password) {
          resolve(false)
       } else {
        
        
        //query mongo
       MongoClient.connect(mongo_uri, async function(err, db) {
            if (err) {
                console.log(err);
            }
            collection_name.find({'email': username}).toArray(function(e,doc){
                if(doc.length === 0) {
                    db.close();
                    resolve(false)
                } else {
                    db.close();
                    resolve(true) 
                }
            });
        })
      }
     }
    }
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading