I have some AngularJS controllers that create graphs from a database data. Before the data is process and the graph render I have to invoke the function GetSensor(x,y), this fucntion return an Id in order to ask for the right data to the database
My problem is that GetSensor(x,y) returns the data way too late. The main function is doing the request with the promise on pending.
I´ve used .then() but still does not wait for the promise to be resolved.
GetSensor():
async function getSensores(Idinfraestrucura, TipoSensorId) {
console.log("whassup")
var xmlhttp = new XMLHttpRequest();
var url = "http://M.Y.I.P:PORT/api/sensores/" + TipoSensorId + "/" + Idinfraestrucura + "";
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
var data = JSON.parse(this.responseText)
console.log(data[0].SigfoxDevice)
return data[0].SigfoxDevice;
}
}
GraphController():
app.controller('HumedadController', ['$scope',
function ($scope) {
let sensor = getSensores(9, 1)
.then(function (response) {
console.log(sensor)
var xmlhttp = new XMLHttpRequest();
var url = "http://My.Y.I.P:PORT/api/grafico/datos/ValorMedicionHumedad/MedicionAire/" + sensor + "";
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var dataURL = JSON.parse(this.responseText);
var dataPoints = dataURL.map(function (elemF) {
return elemF.map(function (o) {
return {
fecha: o.fechaUnix,
Y: o.ValorMedicionHumedad
}
})
});
.
.
.Rest of the code is .render and data transformation
Since I was in a hurry and needed this to work, I had not time to get deep into AngularJS and has to be done this way, so I just created the controllers for the graphs.
May I have getSensores() in, for example, a .service or somthing like that?
Sorry If this is a basic problem that could be solved with a deeper understanding of AngularJS.