Loopback findone function

Viewed 17

I am using loopback on server side of my application , to fetch and validate a data from database I'm using findOne method which is having a callback function. I wanted to get run the callback function as soon as the findone function is executed, The code i have written is working but i want to avoid usage of async-await. Any other alternative for this?

What I tried

 function validId(req) {
        const filter = {
        where: {
            ID: req.id,
        }
    };
    //
    const result = await model.findOne(filter);
    if (result) {
        return true;
    } else {
        return false;
    }
}
module.exports = function () {
    return async function validateTenant(req, res, next) {
        var id = false;
        if (req.url.includes("XYZ")) {
            id = await validId(req)
        }
        //
        if (id || !req.url.includes("XYZ")") {
            next();
        } else {
     
            res.writeHead(404, { "Content-Type": "text/html" });
            var html = fs.readFileSync(
                "error.html"
            );
            res.end(html);
        }
    };
};
1 Answers

you could use the .then() function of the promise

model.findOne(filter).then((result)=>{
   //execute the rest of the function that need to be executed after the findOne.
});
// The code will continue to execute while model.findOne is doing it's thing.

But if you want to wait for the FindOne to give a result without using await or the .then it is not possible unless you make a wrapper of findOne or your BDD package have a synchrone findOne

Related