简体   繁体   中英

Node.js - Break out of callback function and return true/false in the parent functon

I'm using the Node Express framework to build an API and I run into a problem regarding the Basic Auth functionality. I need to run an SQL query to retrieve information about a user and validate their credentials. The issue occurs after the query has been completed. The SQL data is sent into a callback function as shown below. I want to do all the validation inside that callback but I want to break out of the SQL callback and return true/false from the express.basicAuth() function. I have tried setting a global variable and then accessing it outside of the SQL callback but sometimes the query might not have finished by the time that it gets the block that accesses that global variable. Thanks in advance for your help.

var auth = express.basicAuth(function(user, pass) {

    // Query to select information regarding the requested user
    /* Query here to find the requested user's data */

    client.query(query, function (err, rows, fields) {
        if (err) throw err;
        GLOBAL.sql = rows; 

        /* I want to break out of this query callback function and return true from this auth variable */

    });

       // Sometimes the query isn't completed when it gets to this stage
       console.log(JSON.stringify(GLOBAL.sql));


});

express.basicAuth also supports asynchronous operation:

var auth = express.basicAuth(function(user, pass, next) { 
  ...
  client.query(query, function (err, rows, fields) { 
    if (err)
      next(err);
    else
    if (/* authentication successful */)
      next(null, user); // <-- sets 'req.remoteUser' to the username
    else
      next(null, false);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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