Hello and thank you in advance. I'm using npm tedious package to interact with a database. I'm also using Meteor.call and methods, for which I need to pass a variable (newdata in the example below) that carries the data taken from the database as the return value of the function "rr", so that I would be able to use the result of the function in the client by a Meteor call.
function rr(){
var newdata = [];
var ahora = new Request("SELECT * FROM prueba", function (err) {
if (err) {
console.log("err1");
} else {
}
})
ahora.on('row', function(columns) {
columns.forEach(function(column) {
newdata.push(column.value);
});
});
}
I want "newdata" to be the result of the rr function. How can I do that? If I write "return newdata" it's undefined, I can't use await because newdata is not the return value of any function...
Thank you very much.
Tedious doesn't seem to support promises natively, but you can wrap your function in a promise:
function rr() {
return new Promise((resolve, reject) => {
var ahora = new Request("SELECT * FROM prueba", function (err) {
if (err) {
reject(err);
}
});
var newdata = [];
ahora.on('row', function(columns) {
columns.forEach(function(column) {
newdata.push(column.value);
});
});
resolve(newdata);
}
}
Or slightly shorter:
function rr() {
return new Promise((resolve, reject) => {
new Request("SELECT * FROM prueba")
.on("error", reject)
.on("row", function(columns) {
resolve(columns.map(column => column.value))
});
}
}
If you'd rather not make promises manually, you can try Bluebird's promisify function. I also found a tedious-specific promisifying package tedious-promises, but it doesn't seem to be properly maintained.