In Node, the two main (but not only!) ways that you can 'return' from an asynchronous function are:
Callbacks
Similar to how request.query
takes a callback as a parameter, you can also do so:
function myFunction(cb) {
var arr = [];
var connection = new sql.Connection(dbConfig, function (err) {
var request = new sql.Request(connection);
request.query('select top 10 Name from User', function (err, recordset) {
if (err) {
console.log('error');
cb(err, null);
return;
}
for (var id in recordset) {
arr.push(recordset[id]["Name"]);
}
cb(null, arr);
});
});
};
Notice how I've followed the same conventions as other Node callbacks - errors as the first parameter, the returned data as the second parameter. With this in place, you can use your function like so:
myFunction(function (err, data) {
if (err) {
/* error handling */
}
/* do stuff with data here */
});
Promises
A somewhat more modern abstraction around asynchrony is Promises - these represent the asynchronous thing that is going to happen as an object, which will either be resolved or rejected. Here's how you could apply this pattern to your function:
function myFunction() {
return new Promise(function (resolve, reject) {
var arr = [];
var connection = new sql.Connection(dbConfig, function (err) {
var request = new sql.Request(connection);
request.query('select top 10 Name from User', function (err, recordset) {
if (err) {
console.log('error');
reject(err);
return;
}
for (var id in recordset) {
arr.push(recordset[id]["Name"]);
}
resolve(arr);
});
});
});
};
You can then chain .then
and .catch
onto the returned Promise to handle the result:
myFunction()
.then(function (data) {
/* ... */
})
.catch(function (err) {
/* ... */
});
Both of these examples are very basic - there's a lot more you can do, especially when it comes to Promises (which are very well suited to chaining lots of asynchronous stuff together). I'd encourage you to research both of these options further.