How to call an asynchronous service N times - angularjs

Promise in ForEach
I'm having a problem, I need to call a service N times and I've tried this:
This is my function that calls the service, I send a parameter that is "code" and returns a promise.
var get222 = function(codigo) {
var defer = $q.defer();
var cbOk = function(response) {
//console.log(response);
defer.resolve(response);
}
var cbError = function(error) {
//console.log(error);
defer.reject(error);
}
VentafijaAccessService.getProductOfferingPrice(codigo, cbOk, cbError);
return defer.promise;
}
After this function, I get the codes and I need to make a call N times and when they finish returning the promise to get the answer for each code I send.
var getProductOfferingPrice = function(_aCodigoOfertas) {
var deferred = $q.defer();
var results = [];
var promises = [];
angular.forEach(_aCodigoOfertas, function(codigo) {
promises.push(get222(codigo));
});
$q.all(promises)
.then(function(results) {
// here you should have all your Individual Object list in `results`
deferred.resolve({
objects: results
});
});
return deferred.promise;
};
The calls to the services IF THEY ARE EXECUTED, but never returns the promise, I can not get the response of each one.
EDIT
VentaDataService.js
var get222 = function(codigo) {
return $q(function(resolve, reject) {
VentafijaAccessService.getProductOfferingPrice(codigo, resolve, reject);
});
}
var getProductOfferingPrice = function(_aCodigoOfertas) {
return $q.all(_aCodigoOfertas.map(function(codigo) {
return get222(codigo);
}));
};
VentaFijaController.js
var cbOk2 = function(response) {
console.log(response);
}
var cbError2 = function(error) {
console.log(error);
}
VentafijaDataService.getProductOfferingPrice(codigoOfertas)
.then(cbOk2, cbError2)

There's no need to wrap a new promise around this. Just return the $q.all() promise:
VentafijaAccessService.getProductOfferingPriceAllPromise = function(_aCodigoOfertas) {
var promises = [];
angular.forEach(_aCodigoOfertas, function(codigo) {
promises.push(get222(codigo));
});
return $q.all(promises);
};
The resolved value of the returned promise will be an array of results.
VentafijaAccessService.getProductOfferingPriceAllPromise(...).then(results => {
console.log(results);
}).catch(err => {
console.log(err);
});
If _aCodigoOfertas is an array, you can further simply getProductOfferingPrice to this:
VentafijaAccessService.getProductOfferingPriceAllPromise = function(_aCodigoOfertas) {
return $q.all(_aCodigoOfertas.map(function(codigo) {
return get222(codigo);
}));
};
You can also vastly simplify get222() to this:
var get222 = function(codigo) {
return $q(function(resolve, reject)) {
// call original (non-promise) implementation
VentafijaAccessService.getProductOfferingPrice(codigo, resolve, reject);
});
}
Then, in the controller, you could do this:
VentafijaDataService.getProductOfferingPriceAllPromise(codigoOfertas).then(function(result) {
console.log(result);
}).catch(function(e) {
console.log('Error: ', e);
});

Related

angular multiple http looping request with time delay

I have an ID array contains with 50+ id.
var ids = [
'3407197',
'0632706',
'18275',
...,
...
]
I want to send angular HTTP get request with a loop. Each iteration will delay 10 sec delay. When all the request complete it will notify that request are completed.
I have tried with this code but It executes at once not delaying.
function collector(i){
setTimeout(function() {
return $http.get('http://example.com/' + ids[i])
.success(function(data) {
})
.error(function(err) {
})
},10000);
}
$scope.getAllData = function() {
var promises = [];
for (var i = 0; i < ids.length; i++) {
promises.push(collector(i));
}
return $q.all(promises);
}
$scope.getAllData ().then(function(data) {
$scope.debug = 'done';
});
Try with $timeout:
function getRequest(id) {
return $http.get('http://example.com/' + id)
.success(function (data) {})
.error(function (err) {});
}
var promise = $timeout();
ids.forEach(function(id) {
promise = promise.then(function() {
getRequest(id);
return $timeout(10000);
});
});
// not sure if this works
promise.then(function() {
$scope.debug = 'done';
});

Angular Promise - $q.all not returning result and calling Post method several times not working

Am trying to call a Post method and then depending on the result I am going to call same Post method multiple times and return the result, using $q.all.
My Post method is :
getData: function (params, callback) {
$http.post('service/myService', params)
.success(function (data) {
callback(null, data);
}).error(function (error) {
callback(error);
});
}
I am calling it in below function, this function is recursive so if it contains nextUrl I am doing same thing until there is no object for paging:
var result = [];
var promises = [];
var checkForPaging = function (nextUrl, service, $q) {
var deferred = $q.defer();
var criteria = {
url: url
}
var promise = service.getData(criteria, function (error, data) {
if (data.statusCode == 200) {
for (var i = 0; i < data.body.items.length; i++) {
result.push(data.body.items[i]);
}
if (data.body.paging != null && data.body.paging.next != null) {
checkForPaging(data.body.paging.next.url, service, $q);
} else{
deferred.resolve(result);
}
}
});
promises.push(promise);
$q.all(promises)
return deferred.promise;
}
Then am calling this function from below and want to get the result back once all calls are complete:
checkForPaging(data.body.paging.next.url, myService, $q).then(function (data) {
console.log(data)
});
The issue I am having is that it never hits the callback function above : console.log(data). But I can see it calling the Post method several times.
If I resolve it like below then I can see after first Post it is hitting the callback above:
$q.all(promises).then(function (results) {
deferred.resolve(result);
}, function (errors) {
deferred.reject(errors);
});
Am I doing it right? How can I get the result back and call the Post method several times?
Let me know if it is not clear or have any questions!
Try something like this with proper promise chaining:
var result = [];
var checkForPaging = function(nextUrl, service) {
var criteria = {
url: url
}
return service.getData(criteria, function(error, data) {
if (data.statusCode == 200) {
for (var i = 0; i < data.body.items.length; i++) {
result.push(data.body.items[i]);
}
if (data.body.paging != null && data.body.paging.next != null) {
return checkForPaging(data.body.paging.next.url, service);
} else {
return result;
}
}
});
}
checkForPaging(data.body.paging.next.url, myService).then(function(data) {
console.log(data)
});
And getData:
getData: function(params) {
return $http.post('service/myService', params)
.then(function(response) {
return response.data;
});
}
Here is solution: https://plnkr.co/edit/HqkFNo?p=preview I rewrited logic a bit.
You can catch the main idea.
UPDATE added promiseless solution
1) Your service should return only promise:
this.getData = function(url, params){
return $http.post(url, params); //You're just returning promise
}
2) You don't need $q.all, you can use single promise:
var result = [];
var deferred;
var checkForPaging = function (url) {
if(!deferred){
deferred = $q.defer();
}
//resolvind service promise
newService.getData(url).then(
//if ok - 200
function(response){
for (var i = 0; i < data.body.items.length; i++) {
result.push(data.body.items[i]);
}
if (data.body.paging != null && data.body.paging.next != null){
{
return checkForPaging(data.body.paging.next.url);
} else{
deferred.resolve(result);
}
},
//handle errors here
function(error) {
}
);
return deferred.promise;
}
3) You should call it like this:
checkForPaging('url').then(function(data){
//here will be resolved promise
console.log(data);
});

Nested $promise undefined error

I am getting the error Cannot read property of '$promise' of undefined.
Here is the code that is throwing it:
var myPromise = sharedDataService.getData($scope.entityId).$promise;
resolvePromise(myPromise, 'entityData');
the resolvePromise method:
function resolvePromise(promise, resultObject){
promise.then(function(response){
$scope[resultObject] = result;
});
promise['catch'](function(error){
//error callback
});
promise['finally'](function(){
//finally callback
});
sharedDataService looks like this:
var publicInterface = {
getData: getData
};
var storedData;
function getData(entityId) {
if(storedData.entityId === entityId){
return storedData;
}else{
var entityDataPromise = dataAccessService.getEntityData(entityId).$promise;
entityDataPromise.then(function (response) {
storedData = response;
return storedData ;
});
entityDataPromise['catch'](function(error) {
//throw error;
});
entityDataPromise['finally'](function(done) {
//do finally
});
}
}
return publicInterface;
finally, the dataAccessService:
var publicInterface = {
getEntityData: getEntityData
}
var entityData = $resource(apiUrl + 'Entity', {}, {
'getEntityData': {
method: 'GET',
url: apiUrl + 'Entity/getEntityDataById'
}
}
function getEntityData(entityId){
return entityData.getEntityData({entityId: entityId})
}
return publicInterface;
the original promise is throwing an error. When I put breakpoints various places, I can see my data is being returned sometimes. The functionality of sharedDataService is almost one of a chaching service.
Why is my original promise returning undefined?
Your getData() method doesn't have a return when if is false. So you would need to return entitiyDataPromise.
But, that would mean one condition returns a promise and the other returns an object
So both conditions need to return a promise and we can use $q for the first condition
function getData(entityId) {
if(storedData.entityId === entityId){
// return to getData()
return $q.resolve(storedData);
}else{
var entityDataPromise = dataAccessService.getEntityData(entityId).$promise;
// return to getData()
return entityDataPromise.then(function (response) {
storedData = response;
return storedData ;
});
entityDataPromise['catch'](function(error) {
//throw error;
});
entityDataPromise['finally'](function(done) {
//do finally
});
}
}
Be sure to inject $q in service.
In controller would be:
var myPromise = sharedDataService.getData($scope.entityId);
resolvePromise(myPromise, 'entityData');

Asynchronous handling of services who provide data and retrieve it via http when necessary

I have an angularJS app that utilizes two services to retrieve data from a DB.
session.js
angular.module('RiskAssessment').service('session', ['dbInterface', function(dbInterface) {
this.getBatches = function () {
if (!this.batches) {
console.log("Retrieved Batches");
var that = this;
return this.pullBatches().then(function (data) {
that.batches = data; //Is this EVEN possible?
});
} else {
console.log("Didn't retrieve Batches");
}
return this.batches;
};
this.pullBatches = function () {
return dbInterface.pullBatches(this.getUserId());
};}]);
dbInterface.js
pullBatches: function(userId){
return $http.post('db_queries/get_batches.php', userId)
.then(function (response) {
console.log("get_batches.php POST Result: ", response.data);
return response.data;
})
.catch(function (response) {
console.log("Error post");
});
}
I want to able to get this.batches via getBatches() if it has already been retrieved and set. Otherwise, I'd like to use pullBatches() to retrieve and set this.batches. The answer is probably some mix of promises, but I am struggling with this.
Thank you for reading!
EDIT ::
How do I set this.batches within a .then() of my call to .pullBatches()?
this.getBatches = function(){
if(!this.batches) {
console.log("Retrieved Batches");
var deferred = $q.defer();
deferred = this.pullBatches().then(function(data){
//this.batches = data; <---------------------------- HERE
});
return deferred.promise;
}else{
console.log("Didn't retrieve Batches");
}
return this.batches;
};
EDIT 2 ::
With great help from #Jahirul_Islam_Bhuiyan I fixed my issue.
this.getBatches = function(){
var deferred = $q.defer();
if(!this.batches){
console.log("Retrieved Batches");
dbInterface.pullBatches(this.getUserId()).then(function(payload){
deferred.resolve(payload.data);
service.setBatches(payload.data);
});
}else{
console.log("Didn't retrieve Batches");
deferred.resolve(this.batches);
}
return deferred.promise;
};
this.setBatches = function(batches){
this.batches = batches;
};
In Controller...
session.getBatches().then(function(data){
//console.log("getBatches.then() : " + JSON.stringify(data));
$scope.batches = data;
});
I now have a much greater understanding of promises!
Try following
this.getBatches = function(){
var deferred = $q.defer();
if(!this.batches) {
console.log("Retrieved Batches");
this.pullBatches().then(function(data){
deferred.resolve(data);
});
}else{
console.log("Didn't retrieve Batches");
deferred.resolve(this.batches);
}
var promises = [
deferred.promise
];
var promise = $q.all(promises);
return promise;
};
hope this help

How to multi-callback a promise in AngularJs with $q?

I'm using the code below in order to simplify the backend requests but I didn't catch how to call either a success method or an error method.
How can I reach the expected behavior commented in the code?
app.factory('REST', function ($http, $q, sweetAlert) {
return {
load: function (module, action, data) {
var deferred = $q.defer();
var promise = deferred.promise;
$http
.post('/api/'+module+'.php?action='+action, data)
.success(function (data) {
if(data.error)
{
sweetAlert.swal({
title: "Error",
text: data.error,
type: "warning"
});
//HERE I WANT TO CALL .error(details)
}
else
deferred.resolve(data.result);
}).error(function () {
//HERE I WANT TO CALL .error(details)
});
promise.success = function(fn) {
promise.then(fn);
return promise;
}
return promise;
}
};
});
This is the code which uses the code above:
$scope.login = function () {
$scope.loading = true;
var payload = {'credentials': $scope.logindata};
REST.load('access', 'login', payload).success(function(data) {
if(data.redirect)
$state.go(data.redirect);
$scope.loading = false;
}).error(function(data) { //THIS SHOULD BE CALLED
$scope.loading = false;
});
}
First of all, I strongly discourage you from attaching .success to the promise you are returning. This is not Promises/A-compliant, and its subtle difference from .then (as is implemented by $http) causes a lot of confusion. Just return a pure promise.
Other than that, a few things to note:
1) you don't need another $q.defer and deferred.resolve() - just chain to the original promise of $http and return the resulting promise. (see deferred anti-pattern)
2) to reject a promise - that is, to cause the .catch (not .error - see above about the subtle difference) to fire - you should return $q.reject().
All of the above produces the following:
app.factory('REST', function($http, $q, sweetAlert){
return {
load: function(module, action, data) {
// this "return" returns the promise of $http.then
return $http.post('/api/' + module + '.php?action=' + action, data)
.then(function(response) {
var data = response.data; // .then gets a response, unlike $http.success
if (data.error) {
sweetAlert.swal({
title: "Error",
text: data.error,
type: "warning"
});
//HERE I WANT TO CALL .error(details)
return $q.reject(data.error);
}
return data.result; // what you would have "resolved"
});
}
};
})
Then, as I said above, use the .then/.catch as you would with promises:
$scope.login = function () {
$scope.loading = true;
var payload = {'credentials': $scope.logindata};
REST.load('access', 'login', payload)
.then(function(data) {
if(data.redirect)
$state.go(data.redirect);
$scope.loading = false;
})
.catch(function(error) {
$scope.loading = false;
});
}
Update yr code as below
app.factory('REST', function ($http, $q, sweetAlert) {
return {
load: function (module, action, data) {
var deferred = $q.defer();
$http.post('/api/'+module+'.php?action='+action, data)
.success(function (data) {
if(data.error)
{
sweetAlert.swal({
title: "Error",
text: data.error,
type: "warning"
});
//HERE I WANT TO CALL .error(details)
deferred.reject(data.error);
}
else{
deferred.resolve(data.result);
}
})
.error(function (error) {
//HERE I WANT TO CALL .error(details)
deferred.reject(error);
});
return defferred.promise;
}
};
});
for yr controller
$scope.login = function () {
$scope.loading = true;
var payload = {'credentials': $scope.logindata};
REST.load('access', 'login', payload).then(
function(data) {
if(data.redirect)
$state.go(data.redirect);
$scope.loading = false;
},
function(error) {
$scope.loading = false;
});
}

Resources