0

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);
        }
    };
};
4
  • is the parent function defined with an async statement before it's declaration? What is your error? Commented Sep 24, 2022 at 10:48
  • 1
    unclear what is the actual problem... Commented Sep 24, 2022 at 10:49
  • I want to avoid usage of await in the above code Commented Sep 24, 2022 at 11:10
  • 1
    So you are asking us to convert your working code? If you had trouble doing that conversion, then please focus your question on that: provide your attempt, which you thought should have worked, and explain what doesn't work as expected. Commented Sep 24, 2022 at 11:31

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

i tried .then but it was not working in the above condition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.