0
votes

I want to use async and await to handle the promises. I would like to use this on the given example below:

exports.getUserData = async function(userId){
        let query = {};
        if(userId){
            query.where = {userid : req.query.id}
        }
        let data;
        try{
            data = await entity.DB_User.findAll(query);
        }catch(error){
            console.log(error);
        }
    }

On execution its giving me an error

Error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)

1
What line throws the error?CertainPerformance
please provide more details of the codeJithin P
What was the exception that wasn't caught?Quentin
keep your all code inside the method in a try block.Rahul Patil
You are passing a userId to the function and not passing it to where the query if(userId){ query.where = {userid : req.query.id} // userId instead of req.query.id ? }Aditya Kokil

1 Answers

2
votes

First thing first, you should return data.

I think that the Exception is raised when you call getUserData. Try:

getUserData()
    .then(data => console.log)
    .catch(err => console.log) // this line prevent the UnhandledPromiseRejection

// or in async context

try {
    const data = await getUserData()
    console.log(data)
} catch (err) {
    console.log(err)
}