Search code examples
javascriptnode.jsasynchronousrestifynode-mssql

How to return value from a series of cascading async code


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.


Solution

  • 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); });
        });
      }
    }