Node.js MSSQL返回一个值

I have this code

var sql = require('mssql');

....

function dbConnect(){       
sql.connect(config).then(function() {       
    return true;
}).catch(function(err) {
    return false;
}); 

I want the function dbConnect to return a value. But when I call it usingconsole.log(dbConnect()); I got

undefined

Any help?

The dbConnect() function doesn't have a return statement of itself and thus does not return a value, this is to be expected.

Assuming you want to communicate back to the caller whether connecting succeeded you must remember that the process of connecting to the database is asynchronous and must thus be done using a callback (or promise I guess).

If you change your function to something like this:

function dbConnect(cb){       
    sql.connect(config).then(function() {       
        cb && cb(true);
    }).catch(function(err) {
        cb && cb(true);
}); 

You can then call it like this:

dbConnect(function(result) {
    if (result) console.log('yay! connected');
    else console.log('ohnoz! connection failed!');
});

As an alternative you could use a promise structure, but I believe the Node programming style leans more towards callback functions. There is no way however to make the dbConnect function directly return the status of the connection as this value is not yet available when the function is done.