Scope not updating after $http AJAX call [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
The following code is in my controller - when I reach the console.log() line, nothing is printed out. The AJAX call returns a valid array. I tried using $scope.$apply but I got an process already in progress error, I'm assuming because using $http automatically starts the digest cycle:
var mmyApp = angular.module('myApp',['ui.bootstrap']).controller('TasksController', TasksController);
function TasksController($scope, $http) {
$scope.transactions = [];
$http.get('transactions').then(function (response) {
$scope.transactions = response.data;
}, function (error) {
throw error;
});
console.log($scope.transactions);
}

$http.get is asynchronous. When you call your console.log, your GET request didn't return yet. You can move it inside the handle body to see that it works:
$http.get('transactions').then(function (response) {
$scope.transactions = response.data;
console.log($scope.transactions);
}, function (error) {
throw error;
});

You should know that AJAX calls made with $http in AngularJS are asynchronous, that is, they do not run in sequence with the rest of the code, unless you set it that way.
Therefore when the console.log is executed, the request still has not finished processing. The correct thing is that you run console.log after performing the assignment of the variable in the AJAX call, in this way:
var mmyApp = angular.module('myApp',['ui.bootstrap']).controller('TasksController', TasksController);
function TasksController($scope, $http) {
$scope.transactions = [];
$http.get('transactions').then(function (response) {
$scope.transactions = response.data;
console.log($scope.transactions);
}, function (error) {
throw error;
});
}

Related

Array returns empty before getting fullfilled [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
i'm implementing Toast Ui Calendar in my php/js app and in the flow of javascript execution the program encounter this function:
function setSchedules() {
cal.clear();
generateSchedule();
cal.createSchedules(ScheduleList);
refreshScheduleVisibility();
}
When i refresh the page to visualize the events retrived from db via axios and php function, the calendar is empty, then if a select month view or go back one week and come back to the current week the events are rendered.
The problem seam to reside in the function generateScedule() which is declared inside a schedules.js file and that declare and fulfill the ScheduleList array to pass to the createSchedules function, follow the code:
var ScheduleList = [];
function generateSchedule() {
axios({
method: 'post',
url: 'path-to-data',
})
.then(function (response) {
ScheduleList = [];
let data = response.data;
for(let key in data){
ScheduleList.push(data[key]);
};
})
.catch(function (error) {
console.log(error);
});
return ScheduleList; //with or without this return the result doesn't change
}
It's like if the array ScheduleList at first is returned empty (whithout waiting) while the function is still fulfilling it, console.log inside varoius parts of the function confirm it.
If i fulfill the array manually with pasted json data, everything is returned immediately an fine.
I know it has probably to do with javascript stacks etc..
Any help would be appreciated.
Thanks a lot in advance!
Because axios is async so the ShceduleList stay empty,
the return is executed before the loop of data.
Try this :
function generateSchedule() {
return axios({
method: 'post',
url: 'path-to-data',
})
.then(function (response) {
var ScheduleList = [];
let data = response.data;
for (let key in data) {
ScheduleList.push(data[key]);
};
return ScheduleList;
})
.catch(function (error) {
console.log(error);
});
}

AngularJS HTTP use response [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
Hello this is my second time using AngularJS... I create a http request and no problem with it.
But the question is, how i can get the result of this request or put in a variable ?
var cust_url = "RETURN A JSON";
var FINAL_FILE = "";
$http.get(cust_url)
.then(function (response) {
$scope.details = response.data;
//--> do multiple modify to response.data
FINAL_FILE = 'something';
});
$scope.data = {
/*USE HERE --> FINAL_FILE
return -> undefined on console if i try to access to FINAL_FILE
*/
};
Like the example... sorry i think is a stupid error. Thanks for your time.
$http request is asynchronous, this is the reason that you get the undefined value. If you want to use the response data, you have to do it inside the then callback, where the data are available, like this:
$http.get(cust_url)
.then(function (response) {
$scope.details = response.data;
//--> do multiple modify to response.data
FINAL_FILE = 'something';
// here use the $scope.details or call a function to use data
$scope.data = { };
});
Return data to the .then method and save the promise:
var finalFilePromise = $http.get(cust_url)
.then(function (response) {
$scope.details = response.data;
//--> do multiple modify to response.data
FINAL_FILE = 'something';
return FINAL_FILE;
});
To use, extract the data from the promise:
$scope.data = {
//USE HERE --> FINAL_FILE
finalFilePromise.then(function(FINAL_FILE) {
console.log(FINAL_FILE);
});
};
For more information, see
AngularJS $q Service API Reference - Chaining Promises

Asyncronous call using request and getting callback to work within a function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm not very experienced in web things, and I'm trying to make a simple api call within a class. I'm running into the very classic callback problem that new people face, and while there are tons of examples of how to handle this logic, I'm having a really hard time implementing it within a class. I'm using request. Obviously nothing below works, especially in relation to myBody, but I added it to show how I logically thought about it before worrying about asynchronous calls.
const request = require('request);
class GetData{
constructor(){
this.getData();
}
reallyGetData(){
var myData = this.getdata;
return myData;
}
getData(){
//var myBody;
request({'url':`https://somewebsite.com/things.json`, 'json': true }, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
// Successfully returns body as expected
console.log("From inside getData: " + body);
//myBody = body;
});
//return myBody;
}
}
The most useful link I've found explaining how I get the body outside of the getData scope is this one.
However, I'm pretty new to node (and javascript all together), and I can't seem to get the syntax for adding the callback function. Everything I try from examples is invalid syntax, so when I try adding a callback function similar to:
getData(function(result) {
console.log(result);
}
I don't know how to implement this logic within a class.
getData() should be declared to take a function as a "first-class citizen". It might also be called a function pointer.
getData(callback) {
...
callback(result);
}
When calling it, you'll use
getData(function(result) { ... });
You can use the wait operator for it.
const request = require('request');
class Data {
constructor() {
}
async getData() {
var myBody;
await request({ 'url': 'https://somewebsite.com/things.json', 'json': true }, (error, response, body) => {
myBody = body;
});
return myBody;
}
}
(new Data()).getData().then(data => {
// data is the value of response
console.log(data);
});

Always returning function returns undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
There is this small function that should logically returns always, but I am getting undefined :-
function hasAccess() {
var dataObj = {
"id" : $scope.groupId
};
$http.post('http://vlinux:9099/GetItems', dataObj).then(
function(response) {
var result = response.data.result;
if(result.includes($scope.screenId)) {
return "ok";
} else {
return "nok";
}
});
}
I started getting downvotes, so wuickly adding, I debugged it and saw http call is bringing expected response and flow is jumping to the right if/else block. Problem is when I am calling this function in a variable its storing undefined.
The call is simple too :-
var allow = hasAccess();
$http.post is not synchronous, but asynchronous.
Thus, all that you have after $http.post is a promise, not the boolean you are expecting.
The documentation show wells how to provide a "callback" to your function, in case of success as well as failure :
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
// for example : manageWHenOk
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
// for example : manageWHenKO
});
Your function return a result only if the request is fine. If there is an error your function do nothing! I suggest you to add a catch function.
function hasAccess() {
var dataObj = {
"id" : $scope.groupId
};
$http.post('http://vlinux:9099/GetItems', dataObj).then(
function(response) {
var result = response.data.result;
if(result.includes($scope.screenId)) {
return "ok";
} else {
return "nok";
}
}).catch(function (error) {
// do something
});
}
If you still have undefined it means that your template is loaded before to obtain the response. In order to resolve that you can do the request in the resolve method of the $stateProvider.

async JS: why does my variable resolve to undefined? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am getting data from my database. This works.
However, there is something wrong with the flow of my code, I think it has to do with async: Why does facturasDotaciones[ ] (almost last line of code) resolve to undefined?
//npm sql DB access module (https://www.npmjs.com/package/mssql)
var sql = require('mssql');
//sql config object (username, password, etc)
var config = {
bla, bla, bla
}
function traerFacturasDotaciones(){
var request2 = new sql.Request(connection);
request2.execute('seleccionarFacturasCorreosDotaciones', function(err, response, returnValue) {
function peluquiarFacturas(facturas){
for(var i=0;i<facturas[0].length;i++){
facturas[0][i]["CO"]=facturas[0][i]["CO"].trim();
}
return facturas;
}
return peluquiarFacturas(response);
});
}
//get data from server and clean up
var connection = new sql.Connection(config, function(err) {
var request = new sql.Request(connection);
request.execute('seleccionarTiendas', function(err, tiendasRet, returnValue) {
var facturasDotaciones=[];
facturasDotaciones=traerFacturasDotaciones();
console.log("facturasDotaciones", facturasDotaciones);
});
});
traerFacturasDotaciones() doesnt return anything. It calls request2.execute, which calls a callback function passing the response.
One option is that you pass facturasDotaciones to traerFacturasDotaciones as argument and set the value inside that function, but even then it will be assigned in asncy manner. Go through request.execute method to see if it returns promise that you can wait on ?
The function traerFacturasDotaciones does not return anything. Note that the return statement is in a callback function given as second parameter to request2.execute. But that callback is executed asynchronously, and your function traerFacturasDotaciones ends before that callback is executed.

Categories