0

I need some advice on how to re/write the db specific cascading code (callback) so that I can effectively return a value to the underlying if/else.

I am using restify and the db lib is node-mssql (tedious).

function authenticate(req, res, next) {
  var auth = req.authorization;
  var err;

  if (auth.scheme !== 'Basic' || ! auth.basic.username || ! auth.basic.password) {
    authFail(res);
    err = false;
  } else {
    var sql = "SELECT ..."

    var connection = new mssql.Connection(config.mssql, function(err) {
        if (err) {console.log(err);}
        var request = connection.request();
        request.query(sql, function(err, recordset) {
            if (err) {console.log(err);}
            if (recordset.length === 0) {
                authFail(res);
                err = false; // <--- I need to be able to return this
            } else {
                authSuccess();
            }
        });
    });
  }
  next(err);
}

I've reviewed the suggested duplicate, and while I think, I understand the issue, I can't work out the cleanest (lets be honest any) way to get this to work.

schliden
  • 13
  • 3
  • 3
    possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Rodrigo Medeiros Mar 24 '15 at 13:06

1 Answers1

0

How about using Promises?

function authenticate(req, res, next) {
  var auth = req.authorization;

  if (auth.scheme !== 'Basic' || ! auth.basic.username || ! auth.basic.password) {
    authFail(res);
    next(false);
  } else {
    var sql = "SELECT ..."

    var connection = new mssql.Connection(config.mssql, function(err) {
        if (err) {console.log(err);}
        var request = connection.request();
        request.query(sql).then(function(recordset) {
            if (recordset.length === 0) {
                authFail(res);
                return false; // <--- return this
            } else {
                authSuccess();
            }
        }).catch(function(err) {
            console.log(err);
            return err;
        }).then(function(err) { next(err); });
    });
  }
}
Toothbrush
  • 2,080
  • 24
  • 33
  • Fantastic...It works. I've read about promises as the solutions to cascading callbacks. Is the promise something that can be used anywhere/time or does it have to be supported by, in this case the db lib node-mssql ? – schliden Mar 24 '15 at 14:11
  • @schliden Yes, the library has to support them for it to work out of the box. – Toothbrush Mar 24 '15 at 15:43