javascriptexpressasync-awaitasync.jsawaitility

Console statment not waiting for the function return in javascript


I'm trying to initialize a variable x to the value returned by the showData function. Here's my code:

app.post("/view/show", (req,res) => {
    let x = showData(req.body.custmerName);
    console.log(x);
}

And here is the showData function:

const showData = (custName) => {
    const customer = mongoose.model(custName ,collectionSchema,custName);
    customer.find( (error,data) => {
        if (error){
            console.log(error);
        }else{
            return data;  
        }
    });
}

However, the console shows undefined. If I add console.log(data) to the showData function, I can see that I was able to successfully fetch data from the database.

I understand that console.log(x) is not waiting for the execution of showData(), due to the synchronous property of JavaScript. How can I get the value from the function and log it to the console, instead of getting undefined?


Solution

  • You can use async/await or callback when dealing with the async functions.

    app.post("/view/show", (req,res) => {
      showData(req.body.custmerName, (err, res) => {
        const x = res;
        console.log(x);
      });
    });
    
    const showData = (custName, callback) => {
      const customer = mongoose.model(custName ,collectionSchema,custName);
      customer.find(callback);
    }