I'm trying to run a sequence (one at at time, not in parallel) of promises for http GETs. Think of submitting a cooking recipe and the server will only accept one step per HTTP request. And they have to be sent in order or the pie will be a mess. And the last step is the only one returning data (a hot apple pie).
I have created a Plunker http://plnkr.co/edit/yOJhhw?p=preview
We'll start with the controller
angular.module("app")
.controller("sequencialCtrl", ["$scope", "seq", function($scope, seq) {
The controller starts with a list of steps represented by library files so they will take >0 time to d/l.
var recipeSteps = [
'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js',
'https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js',
'https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js'
];
Then I create a inters scope variable to display the first 80 chars of the retrieved js files for testing purposes only.
$scope.inters = seq.intermediates;
Then I try to call the factory provided promise. This crashes in the console at the then
// the console shows that seq.submitRecipe is undefined
seq.submitRecipe.then(function(data) {
$scope.results = data;
});
}]);
Now the Factory
angular.module('app').factory('seq', function($http, $q) {
and we create intermediates and submitRecipe
var intermediates = ['test1', 'test2'];
var submitRecipe = function(theSteps) {
var deferredRecipe = $q.defer();
var deferredPromise = deferredRecipe.promise;
deferredPromise
.then(function() {
var deferred = $q.defer();
var promise = deferred.promise;
$http({
method: 'GET',
url: theSteps.shift()
}).then(function(response) {
intermediates.push( response.data.substr(0, 80) );
deferred.resolve(response.data.substr(0, 80));
});
return promise;
})
.then(function() {
var deferred = $q.defer();
var promise = deferred.promise;
$http({
method: 'GET',
url: theSteps.shift()
}).then(function(response) {
intermediates.push( response.data.substr(0, 80) );
deferred.resolve(response.data.substr(0, 80));
});
return promise;
})
.then(function() {
var deferred = $q.defer();
var promise = deferred.promise;
$http({
method: 'GET',
url: theSteps.shift()
}).then(function(response) {
intermediates.push( response.data.substr(0, 80) );
deferred.resolve( "Apple Pie");
});
return promise;
});
As noted before I only want to return the data from that last then which is "Apple Pie".
We close out the submitRecipefunction with...
// if this resolve isnt here, nothing is execute
deferredRecipe.resolve();
$rootScope.$apply();
return deferredPromise;
};
I have found that if I dont have that resolve() the thens aren't run.
And finally we expose our factory's methods.
return {
submitRecipe: submitRecipe,
intermediates: intermediates
};
});
At the end of the day I would like $scope.results to be "Apple Pie".
Appreciate any help.