Can not assign a value after another function run success javascript [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have some code like this
I have load function, it call testRequest function.
testRequest function call ajax service and return response.
But after testRequest function run success, load function get undefined value
angular.module('MyApp', []).controller("AppCtrl", ['AjaxService', function(ajax) {
var l_this = this;
this.testRequest = function() {
var req = ajax.getstatus('https://testapi.io/api/nguyenthemanh2601/testangular');
req.then(function(rep) {
var arr = [];
if (rep.status == 400) {
for (i = 1; i < 10; i++) {
arr.push(rep.data + i);
}
return arr;
} else {
for (i = 1; i < 10; i++) {
arr.push(rep.data + i);
}
return arr;
}
});
};
this.load = function() {
var res = l_this.testRequest();
console.log(res);
l_this.status = res;
}
}]);
Please help!

angular.module('MyApp', []).controller("AppCtrl", ['AjaxService', function(ajax) {
var l_this = this;
this.testRequest = function() {
$http({
method: 'POST',
url: 'https://testapi.io/api/nguyenthemanh2601/testangular',
}).
success(function(rep) {
if (rep.status == 200) {
for (i = 1; i < 10; i++) {
arr.push(rep.data + i);
}
return arr;
}
}).
error(function(rep) {
if (rep.status == 400) {
for (i = 1; i < 10; i++) {
arr.push(rep.data + i);
}
return arr;
}
});
};
// Next Execution.....
}]);
Note You can handle success and error message based on that response execute the next step(handle error and success).
more info... $http request angular

Related

$.when apply for single request

I am trying to use $.when apply in my code. However, it seems that the format return is different for single and multiple request. How can i cater for it?? I am trying not to have another if else outside of it.
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});
This is what i do not want to do.
if (apiRequestList.length === 1) {
$.ajax({
});
} else {
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});
}
You can simply convert arguments into an array, when the length of apiRequestList is 1:
$.when.apply(null, apiRequestList).then(function() {
var _arguments = Array.prototype.slice.call(arguments);
if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
_arguments = [arguments];
for (var i = 0; i < _arguments.length; i++) {
var value = _arguments[i][0];
console.log(value);
}
});
Live Example on jsFiddle (since we can't do ajax on Stack Snippets):
function x(a) {
return $.post("/echo/html/", {
html: "a = " + a,
delay: Math.random()
});
}
function doIt(apiRequestList) {
$.when.apply(null, apiRequestList).then(function() {
var _arguments = arguments;
if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
_arguments = [arguments];
for (var i = 0; i < _arguments.length; i++) {
var value = _arguments[i][0];
console.log(value);
}
console.log("----");
});
}
doIt([x(1), x(2), x(3)]);
doIt([x(4)]);
Example output (it'll vary because of the Math.random()):
a = 4
----
a = 1
a = 2
a = 3
----

How can I access the returned value from a service factory function in angularJS [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm new to AngularJS, and I am trying to access a returned value from a Factory Service Function myFactoryService, in order to use it in my Controller:RequestsController.
The code goes like this. First we have HolidaysService. This is responsible for obtaining an array of Dates from the server side (in C#) and returns it if the operation was successful:
app.factory('HolidaysService', function ($http) {
var fac = {};
fac.getHolidays = function (d) {
return $http({
method: 'GET',
url: '/RequestAng/getHolidays'
}).then(function successCallback(response) {
var dates = []; // empty array of Holidays
var i = 0;
var counter = 0;
for (var i in response.data) {
dates[i] = new Date((parseInt(response.data[i].substr(6)))); // parsing the returned JSON Values.
i++;
}
return dates;
}, function errorCallback(response) {
console.log(response);
});
}
return fac;
});
Then I have another Factory which uses HolidaysService,defined above, in order to get the array of dates and do some computations:
app.factory('myFactoryService', function (HolidaysService ) {
var service = {};
var counter = 0;
service.Calc = function (d1, d2) {
HolidaysService.getHolidays().then(
function (dates) {
var i = 0;
for (i in dates) {
if (dates[i] >= d1 && dates[i] <= d2) {
if (dates[i].getDay() != 6 && dates[i].getDay() != 7) {
counter++; // This is the value I need to access in the controller later on
}
}
i++;
}
return counter;
}
);
}
return service;
});
Now I want to use the returned value from myFactoryService in my RequestsController as follows:
(function () {
var app = angular.module('RM', ['ui.date']);
app.controller('RequestsController', function ($scope, $http, myFactoryService) {
$scope.counter=0;
$scope.Request = {
Remaining: '',
DateRequest: new Date(),
DateBeg: '',
DateEnd: ''
};
/* This is to change the Changing 'Remaining' Input TextField if Dates are changed */
var names = ['Request.DateBeg', 'Request.DateEnd'];
$scope.$watchGroup(names, function (newValues, oldValues, $scope) {
var businessDays = $scope.CalcBusinessDays(); // Calculates business days between two dates
if (businessDays != -1) {
var x = 1;
x = myFactoryService.Calc($scope.Request.DateBeg,$scope.Request.DateEnd);
console.log("printing x: " + x);
}
});
});
Now when I try to access the value returned from myFactroryService, I always get undefined. Any ideas? Thanks in advance. (Sorry for the long post)
I think you miss a return in front of HolidayService:
service.Calc = function (d1, d2) {
return HolidaysService.getHolidays().then(
// rest of code ignored
And here:
x = myFactoryService.Calc($scope.Request.DateBeg,$scope.Request.DateEnd);
x is actually a promise. You can do:
x.then(function(xval) { console.log("printing x: " + xval); }

Javascript global variable - console log undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have problem with this line
console.log("xxx" + stanica1);
Result is xxxundefined but i need return value stanica1Prosjek/24;
function podatciPrethodniDan(handleData) {
var parametar = $("#parametar1").val();
$.ajax({
type: "POST",
url: "php/getPreviousDayData.php",
dataType: "json",
data: {
parametar: parametar
},
success: function(data) {
handleData(data);
} //end of success
}); //end of ajax
}
function style(feature) {
var stanica1;
stanica1 = podatciPrethodniDan(function(output) {
//console.log(output);
var stanica1Prosjek = 0;
var stanica2Prosjek = 0;
var stanica3Prosjek = 0;
var stanica4Prosjek = 0;
//console.log(output.length);
for (i = 0; i < output.length; i++) {
//console.log("petlja " + i);
if (i < 24) {
stanica1Prosjek = stanica1Prosjek + parseFloat(output[i].par);
//console.log(stanica1Prosjek + " " + i);
}
}
console.log("in" + stanica1Prosjek);
return stanica1Prosjek / 24;
});
console.log("xxx" + stanica1);
}
Define you var out of functions.
Example:
var demo = 12;
function ok () {
demo += 3;
}
function ok2 () {
demo+= 5;
}
console.log( demo ); // return 12
ok();
console.log( demo ); // return 15
ok2():
console.log( demo ); // return 20

AngularJS multiple $http calls, with multiple results

I have a LIST of Id's and I want all of them to contact my API.
The way I did it is like this:
var someFunct = function() {
for (var i = 0; i < Apples.length; i++) {
var Apple = Apples[i];
$http.get("APIUrl" + Apple.Id).
success(function (response) {
for (var i = 0; i < response.Appleseeds.length; i++) {
if(Apple.Appleseeds.Id == response.Appleseeds.Id)
{
Apple.Size = response.Appleseeds.Size;
}
}
})
}
So the problem is that Apple[2] has changed value, where Apple[0] and Apple[1] stay untouched. response.Appleseeds have their own list of Id's. So I need to change the Size of ALL THE APPLES not just Apple[2].
You're close, use a closure instead:
var someFunct = function () {
for (var i = 0; i < Apples.length; i++) {
(function (Apple) {
$http.get("APIUrl" + Apple.Id)
.success(function (response) {
for (var i = 0; i < response.Appleseeds.length; i++) {
if (Apple.Appleseeds.Id == response.Appleseeds.Id) {
Apple.Size = response.Appleseeds.Size;
}
}
});
})(Apples[i]);
}
};
Because http doesn't happen instantly, by the time the last success has happened in your code apple has been changed. By wrapping it in a closure you make it so that each call has it's own private Apple.
var deferred = $q.defer();
var someFunct = function() {
for (var i = 0; i < Apples.length; i++) {
$http.get("APIUrl" + Apples[i].Id).
success(function (response) {
deferred.resolve(response)
})
return deferred.promise;
}
}
someFunct().then(function(d)){
// write your code here
}

AngularJS: $http response too slow

I am using this code:
$http.get('/api/users').
success(function(data) {
$scope.authors = data;
}).
error(function() {
console.log('API error - config.')
});
And somewhere below (much bellow):
for (var i = 0; i < $scope.authors.length; i++) {
...
};
Sometimes it happens that $scope.authors are not avaliable yet. Is there any way to solve this?
UPDATE
This is the whole block structure:
// author
$http.get('/api/users').
success(function(data) {
$scope.authors = data;
processAuthors();
}).
error(function() {
console.log('API error - config.')
});
// if updating form
$scope.$on('$routeChangeSuccess', function() {
if($routeParams.id) {
$http.get('/api/offers/' + $routeParams.id).
success(function(data) {
// author
function processAuthors() {
for (var i = 0; i < $scope.authors.length; i++) {
if($scope.authors[i].email == data.author.email) {
$scope.author = $scope.authors[i];
};
};
}
Put the loop in the succes part:
$http.get('/api/users').
success(function(data) {
$scope.authors = data;
for (var i = 0; i < $scope.authors.length; i++) {
...
};
}).
error(function() {
console.log('API error - config.')
});
Yes, it doesn't matter how much below it is - you still need to call it from inside the callback because it's an async call:
function processAuthors() {
for (var i = 0; i < $scope.authors.length; i++) {
...
};
}
And then:
$http.get('/api/users').
success(function(data) {
$scope.authors = data;
processAuthors();
})
I used a function to make it look cleaner, but you can copy your code that depends on the callback inside it.
UPDATE
function processAuthors(data) {
for (var i = 0; i < $scope.authors.length; i++) {
if($scope.authors[i].email == data.author.email) {
$scope.author = $scope.authors[i];
};
};
}
$scope.$on('$routeChangeSuccess', function() {
if($routeParams.id) {
$http.get('/api/offers/' + $routeParams.id).
success(function(data) {
// author
processAuthors(data); // just call it here, define it outside

Categories

Resources