Wait for $http promise before the next request - javascript

I'm working on an angularJS app and this is my first website using this framework. In my app i've a need to make a $http call inside a for loop. With in the loop before the next iteration I want to wait for the response from my previous call. What is the best and simple way to do this. I've tried using the callBack, $q.all(), .then in all of these only the last request is going through. Please help.
Note: My API that i'm calling through $http can't queue requests.
Edit:
I've tried both the below approaches, in both of the cases only the last request is being made successfully. Can you tell me what is wrong i'm doing here.
Approach 1:
var promiseArray=[];
for(var i=0;i<items.length;i++)
{
var promise=services.Post(items[i]);
promiseArray.push(promise);
}
$q.all(promiseArray).then(data)
{
...
}
Approach 2:
var promises = [];
for (var i = 0; i < items.length; i++) {
var deffered = $q.defer();
var promise = services.Post(items[i]);
promise.success(function(data) {
deffered.resolve(data);
})
promises.push(deffered);
}
var result = $q.all(promises);
EDIT :2
Service Code:
Services.Post = function(lineItemId, submitUrl) {
var url = (submitUrl) ? submitUrl : Services.serviceUrl;
return $http.post(url, {
"LineItemID": lineItemId
}).
success(function(data, status, headers, config) {
Services.processResponse(data, status, headers, config);
}).
error(function(data, status, headers, config) {
JL('Angular').error('Error response when calling Service ' + config);
});
};

You could use $q.when which would take promise of $http & when it gets resolved it call the function inside .then
$q.when(promiseObj).then(callback);
If there are multiple promise then you could use $q.all which would accept array of promise & called then function when all promise inside the function gets resolved.
$q.all([promiseObj1, promiseObj2]).then(callback);
Update
I think your 1st approach is right only missed couple thing
for loop condition, which does create an extra object which would be undefined
$q.all should have function inside .then
Code
var promiseArray=[];
for(var i=0; i < items.length - 1;i++) //<-- change from i<items.length
{
var promise=services.Post(items[i]);
promiseArray.push(promise);
}
$q.all(promiseArray).then(function(data) //<-- it should be function in .then
{
//this will called after all promises get resolved.
});

Related

Using promise with closure in service with multiple $http.get

I've searched high and low but I just can't seem to wrap my head around q.defer() and creating my own promise.
I have a service getDataService which does exactly that - $http.gets data from a REST server. However only one of each variable can be sent at a time, so if user wants to query server for two entities and return the entire associated data they must send two requests. Because of this I had to use a method which kept i as the actual count (closure) which then runs my get data function the appropriate amount of times:
keepICorrect: function (security) {
var self = this;
for (var i = 0 ; i < entity.length; i++) {
self.getDataFromREST(security, i);
}
},
I call this from my main controller as a promise :
$scope.apply = function (security) {
var myDataPromise = getDataService.keepICorrect(security);
myDataPromise.then(function () {
//DO STUFF
}, 1);
}, function (error) {
alert("Error Retrieving Data");
return $q.reject(error);
});
}
This worked when using .getDataFromREST() but obviously doesn't now as I have to route through my new loop function, keepICorrect().
My question is how on earth do I create a promise which spans from my service to my controller, but not only that, also waits to resolve or fail depending on whether the i amount of requests have completed?
You need to create an array of promises
keepICorrect: function (security) {
var self = this;
var promises = [];
for (var i = 0 ; i < entity.length; i++) {
promises.push(self.getDataFromREST(security, i));
}
return promises;
},
And then wait for all of them to complete using the $q library in Angular
$q.all(getDataService.keepICorrect(security))
.then(....

Handling multiple Ajax Requests inside another Ajax Request

I'm using angularjs' $http method to get multiple "parent" elements. In this Ajax Calls .success method, I have to iterate over the parent elements, and use yet another Ajax call for every parent element, to get its respective child elements. What I want in the end, is an Array containing all the child element objects, so I can display them using ng-repeat. That's why I want to collect all the child elements in an array first, and the write that array to the scope array I'm using to display, so angular will only update when all child elements are collected. I'm not that versed in using promises, but I think this should be possible by using them. The structure is basically:
.success(function(parentElements){
var tempChildElements = [];
$.each(parentElements, function(i, parentElement){
getChildElements(parentElement)
.success(function(childElements){
tempChildElements.concat(childElements);
})
})
});
$scope.childElements = tempChildElements;
});
Basically, I need to know when all the requests inside jQuery.each are finished.
EDIT:
So, I changed my code to incorporate your answers, and I think I'm close but it's still not working. What I got is:
$scope.loadChildren = function(){
var tempchildren = [];
var promises = [];
restApi.getOwnparents() //Returns $http.get promise
.then(function(parents){
parents.data.forEach(function(parent, i, parents){
promises.push(restApi.getOwnchildren(parent) //Returns $http.get promise
.then(function(children){
tempchildren = tempchildren.concat(children.data);
},function(msg){
console.log(msg);
}));
});
}, function(msg){
console.log(msg);
});
$q.all(promises).then(function(data){
//Never gets called
$scope.currentElements = tempchildren;
console.log(tempchildren);
});
};
EDIT 2:
I got it to work using suggestions from you guys, below is my code. Feel free to share improvements.
$scope.loadparents = function(){
var tempchildren = [];
var promises = [];
restApi.getOwnparents()
.then(function(parents){
parent.data.forEach(function(parent, i, parents){
promises.push(restApi.getOwnchildren(parent));
});
$q.all(promises).then(function(data){
console.log(data);
data.forEach(function(children){
tempchildren = tempchildren.concat(children.data);
});
$scope.currentElements = tempchildren;
});
});
};
Something like this might be a possibiliy. Loop through your parentElements calling getChildElements with that element. However the response from getChildElements will be a promise if your returning the $http call so push that into an array and pass that array to $q.all. When all your ajax calls resolve so will $q.all.
var parentElements = [10, 20, 30, 40],
promises = [];
parentElements.forEach(function(i){
//Each method is actually called here
promises.push(getChildElements(i));
});
//$q.all will resolve once all of your promises have been resolved.
$q.all(promises)
.then(function (data){
//handle success
console.log('All Good', data);
//Modify your response into what ever structure you need, map may be helpfull
$scope.childElements = data.map();
});
Most likely your ajax call won't be resolved by the time the array is passed to $q.all however another nice thing about promises is even if they are all resolved $q.all will resolve straight away instead.
See it in action. http://jsfiddle.net/ht9wphg8/
Each request itself returns a promise, which can then be put into an array and pass that array to $q.all().
The success() callback is deprecated and since you need to return promises you need to use then() anyway in your original request callback.
Here's a sample factory that would make all the requests and once done you would have the parent data of first request returned to controller:
app.factory('DataService', function($http, $q) {
return {
getData: function() {
// return initial promise
return $http.get('parent.json').then(function(resp) {
var parentArr = resp.data;
// create array of promises for child data
var promises = parentArr.map(function(parentItem, i) {
// return each child request promise to the array
return $http.get('child.json').then(function(resp) {
console.log('Child request #' + (i + 1) + ' completed');
// update parent item
parentItem.child = resp.data
});
});
// return the promise wrapping array of child promises
return $q.all(promises).then(function() {
console.log('All requests completed');
// when all done we want the parent array returned
return parentArr;
});
});
}
};
});
app.controller('MainCtrl', function($scope, DataService) {
DataService.getData().then(function(parentArr) {
console.log('Add data to scope')
$scope.parentArr = parentArr;
});
});
DEMO

success and error function in the controller for a service

I have the following code in a service and I am calling fetchData function from the controller.
Service
app.service("geturl", function($http) {
urllist = [];
geturl.fetchData = function() {
var data = [];
for (i = 0; i < urllist.length; i++) {
(function(index) {
return $http.get(geturl.urllist[index], {
timeout: 8000
})
.then(function(response) {
data[index] = response.data;
});
}(i);
return data;
});
};
});
I want to write the success and error function of $http.get in the controller since it is needed in the UI, how can I go about it?
..I want to write the success and error function of $http.get in the
controller..
Usually, the .then() function takes two function arguments. The first argument is the success handler and the second as an error handler.
$http.get(url,options).then(function (response){
//success handler function
},function(error){
//error handler function
})
Alternatively, you can specify the .success and .error functions separately.
$http.get(url,options).success(function (response){
//success handler function
}).error(function(error){
//error handler function
})
UPDATE:
From your code, it seems that you intend to return something from your service geturl and providing the callbacks there itself. This is not how it is supposed to be done. You should return a promise from your service .
...
app.service("geturl",function($http){
...
getData:function(){
return $http.get(url,options);
}
...
});
...
and handle the success/error callbacks in the module where you are consuming the service
geturl.getData().success(function(){
//handle success
}).error(function(){
//handle error
})
In case you need to make multiple http requests, never ever use the for loop . Remember, everything is asynchronous and you are not guaranteed to get the response from one of the previous request before you make a new one. In such scenarios, you should use $q service. See #pankajparkar's answer for more details
Seems like you want to return a data after all the ajax gets completed, You could achieve this by using $q.all()
Service
app.service("geturl", function($http, $q) {
this.urllist = [];
this.fetchData = function() {
var data = [], promises = [];
for (i = 0; i < urllist.length; i++) {
(function(index) {
var promise = $http.get(geturl.urllist[index], {
timeout: 8000
})
.then(function(response) {
data[index] = response.data;
});
promises.push(promise); //creating promise array
}(i);
};
return $q.all(promises).then(function(resp){
return data; //returning data after all promises completed
});
};
});

Structuring promises within angularjs

I have done a lot of reading around this, but ultimately the tutorials and guides I have found differ too much for me to get a decent grasp on this concept.
This is what I want to achieve:
1) Simple http request from our server [Any API for demonstration]
2) Run a function with data from (1). [Remove a property from the object]
3) Use result and length of (2) to run a loop of $http requests to our server. [Or any server]
4) This will result in 6 different objects. Run a function on these 6 objects. [Add a property]
5) Once ALL of this is done, run a separate function [Log "finished"]
How can this be achieved using promises? How do I pass data from (1) via a promise to (2)? Is this the right way to achieve what I need to do?
If anyone can show me how this should be structured it would be immensely helpful; I have kept the functions as simple as possible for this question.
Yes, promises are very nice to structure solutions for this kind of problems.
Simplified solution (more or less pseudo-code):
$http(...)
.then(function(response) {
// do something with response, for example:
var list = reponse.data.list;
// return it so that you can use it in the next 'then'.
return list;
})
.then(function(list) {
var promises = [];
angular.forEach(list, function(item) {
// perform a request for each item
var promise = $http(...).then(function(itemResponse) {
itemResponse.extraProperty = true;
return itemResponse;
});
// we make an array of promises
promises.push(promise);
});
// combine all promises into one and return it for the next then()
return $q.all(promises);
})
.then(function(itemsList) {
// itemsList is now an array of all parsed item responses.
console.log(itemsList);
});
(Hopefully this is right, I did not tested it.)
As you can see, you can return values in a callback to pass it to the next then(), or you can pass a promise, and this will result in calling the next callback when it resolves. $q.all() is used to combine multiple promises into one and resolve if all are resolved.
Edit: I realised that you can optionally leave out these three lines:
return list;
})
.then(function(list) {
But it is nice syntax though, because the separation of tasks is more visible.
Check code below, it could contains syntax error, the important is the structure. Step3 contains multiple(6) $http requests, it waits until the last request response to return a unique response object (array) containing response for each $http requets.
//Step 1
var Step1 = function () {
$http.get('api/controller').success(function (resp) {
var object1 = resp;
Step2(object1);
Step3(object1).then(function (resp) {
//resp.data is an array containing the response of each $http request
Step4(resp);
Step5();
});
});
}
//Step2
var Step2 = function(obj){
//do whatever with the object
}
//Step3
var Step3 = function (object1) {
var call = $q.defer();
var get1 = $http.get(object1[0].url);
var get2 = $http.get(object[1].url2);
//...
var get6 = $http.get(object[5].url6);
$q.all([get1, get2,..get6]).then(function (resp) {
call.resolve(resp);
});
return call.promise;
}
//Step4
var Step4 = function (resp) {
for (var i=0; i<resp.data.lenght;i++){
DoWhatEver(resp.data[i]);
};
}
//Step5
var Step5 = function () {
alert("Finished");
}
Step1(); //Call Step1 function
Don't know why you have difficulty implementing this, but maybe $q.all() is what you're missing:
var config1={method:'GET',url:'/api/...'};
$http(config1).success(function(resultsFrom1){
functionForResultsOf1(resultsFrom1);
})
var functionForResultsOf1 = function(resultsOf1){
//remove something from the result, assuming this is a synchronous operation
resultsOf1.splice()...;
var promises=makePromises(*pass whatever you want*);
$q.all(promises).then(function(aggregateOfAllCallsToServer){
angular.forEach(aggregateOfAllCallsToServer,function(data){
//do something to data from each call to the server
})
console.log("finished");
})
}
var makePromises = function(serverUrls){
var promises = [];
angular.forEach(serverUrls, function(url) {
var promise=$http({
url : '/api/'+url,
method: 'GET',
})
promises.push(promise);
});
return $q.all(promises);
}

AngularJS collecting data in a loop of $http calls

I have the following loop which I have to make on my client API. On each iteration of loop I must add data returned from the API call as an object to an object array, then at the end of the loop I need to display the content of the object array.
Due to the nature of JS code execution (asynchronous) displaying the object array content always return undefined, so I was wondering if someone can please help me with a solution to this problem. Thanks.
var invoiceObj = {};
var invoiceObjArray = [];
for (var i=0; i< 5; i++)
{
//getAllInvoices returns a promise from $http.GET calls...
ClientInvoiceService.getAllInvoices(i).then(function(invoice){
invoiceObj = { invoiceNum: invoice.Result[0].id,
clientName: invoice.Result[0].clientName};
invoiceObjArray.push(invoiceObj);
}, function(status){
console.log(status);
});
}
console.log(invoiceObjArray[0]); //return undefined
console.log(invoiceObjArray[1]); //return undefined
What you'll need to do is store all promises and then pass these to $q.all (scroll all the way down), which will wrap them in one big promise that will only be resolved if all are resolved.
Update your code to:
var invoiceObj = {};
var invoiceObjArray = [];
var promises = [];
for (var i=0; i< 5; i++)
{
//getAllInvoices returns a promise...
promises.push(ClientInvoiceService.getAllInvoices(i).then(function(invoice){
invoiceObj = { invoiceNum: invoice.Result[0].id,
clientName: invoice.Result[0].clientName};
invoiceObjArray.push(invoiceObj);
}, function(status){
console.log(status);
}));
}
$q.all(promises).then(function(){
console.log(invoiceObjArray[0]);
});
This Egghead video is a nice tutorial to using $q.all:

Categories

Resources