0

I am trying to return a true / false value from validateKey, but am having problems resolving the promise. I have tried return new Promise, but am a bit stuck.

server.js

app.get("/node/api/mssql/test", function(req, res) {
  console.log(session.validateKey(req)) // logs: Promise { <pending> }, would like to log: true or false
})

session.js

exports.validateKey = function(req) {
  return sql.connect(config.properties)
    .then(pool => {
      return pool.request()
        .query("SELECT CASE WHEN EXISTS (SELECT * FROM Login WHERE (username = '" + req.header("username") + "' AND apiKey = '" + req.header("apiKey") + "')) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END")
        .then(response => {
          console.log(response[0]['']) // returns true / false
          return response[0][''] // return nested value to get true / false response
        })
   })
}

How can I return a promise from validateKey that contains the result of response[0]['']?

Matthew
  • 1,461
  • 3
  • 23
  • 49
  • As yBrodsky says, your validateKey already correctly returns a promise, although you have more nesting than is necessary/idiomatic. FWIW: https://pastebin.com/jtpYxPQh – T.J. Crowder Jan 04 '18 at 18:17

2 Answers2

1

Your function validateKey already returns a promise. The problem is how you use it.

session.validateKey(req).then((validation) => {
  console.log(validation) //true or false

  //if you want to return this value
  return res.send({result: validation});
});
yBrodsky
  • 4,981
  • 3
  • 20
  • 31
  • I would like to chain it, so if true, then run another function. More context is here: https://stackoverflow.com/questions/48099233/resolve-expression-from-node-api-endpoint-boolean – Matthew Jan 04 '18 at 18:15
  • You could chain it, the problem is that if you put something chained to that `then` you won't be able to call `return res.send...` inside that `then` without it going to the chained `then` (tongue twister) – yBrodsky Jan 04 '18 at 18:16
  • 1
    @Matthew: `session.validateKey(req).then(valid => { if (valid) { otherFunction(); } });` (plus error handling, of course). – T.J. Crowder Jan 04 '18 at 18:17
0

Just use an async middleware:

app.get("/node/api/mssql/test", async function(req, res) {
 const isValid = await session.validateKey(req));
 console.log(isValid);
 res.end(isValid ? "Logged in!" : "Failed");
})
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151