简体   繁体   English

如何从一系列级联异步代码中返回值

[英]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. 我需要一些有关如何重新/编写特定于数据库的级联代码(回调)的建议,以便可以有效地将值返回给基础的if / else。

I am using restify and the db lib is node-mssql (tedious). 我正在使用restify,数据库库为node-mssql(乏味)。

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. 我已经审查了建议的重复项,尽管我认为我理解这个问题,但是我无法找到最干净的方法(老实说)使它生效。

How about using Promise s? 使用Promise怎么样?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM