0

I´m making a RESTful api with node/express. And I´m having trouble with the asynchronous part of javascript

For example, I have this:

function isWorkMine(workdata) {
    var result = false;
    Work.otherQueryToTheDB(workdata,(err,data) => {
        if (data.length > 0) {
            result = true;
        }
    });
    return result;
};

router.get("/works", (req, res) => {
    const workdata = {...}

    var result = isWorkMine(workdata);
    if (result) {
        Work.queryToTheDataBase(state,(err,data) => {
            if (data.length == 0) {
                return res.status(404);
            }
            res.json(data);
        }); 
    } else {
       console.log("Do Nothing!");
    }
});

The problem with this is that result is always false. I tried

async function isWorkMine(workdata) {
        var result = false;
        await Work.otherQueryToTheDB(workdata,(err,data) => {
            if (data.length > 0) {
                result = true;
            }
        });
        return result;
    };

But it didn´t work. What I am doing wrong?

daniel gon
  • 159
  • 2
  • 14
  • You can only `await` a promise. `Work.otherQueryToTheDB` accepts a callback and is not returning a promise. – Quentin Nov 06 '18 at 14:17
  • You're using async function and expect them to be sync. Thats why, take a look at async / await. Or use proper Promises or Callbacks. – YeppThat'sMe Nov 06 '18 at 14:57

0 Answers0