Skip to content

Instantly share code, notes, and snippets.

@jdnichollsc
Last active June 8, 2021 00:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jdnichollsc/89aa64bffda68312ecfd3acd6294f1cc to your computer and use it in GitHub Desktop.
Save jdnichollsc/89aa64bffda68312ecfd3acd6294f1cc to your computer and use it in GitHub Desktop.
Angular mapSeries like Bluebird.js
(function () {
'use strict';
angular
.module('App')
.factory('Async', Async);
Async.$inject = ['$q'];
function Async($q) {
return {
mapSeries: function (items, asyncFunc) {
items = items || [];
asyncFunc = asyncFunc || function(){ return $q.when(); };
var index = 0;
var deferred = $q.defer();
var promise = asyncFunc(items[index], index, items.length);
var addChain = function (){
promise = promise.then(function () {
checkNextPromise();
}).catch(function (error) {
deferred.reject(error);
});
};
var checkNextPromise = function () {
index++;
if (index < items.length) {
promise = promise.then(function () {
deferred.notify(index / items.length);
return asyncFunc(items[index], index, items.length);
});
addChain();
}
else {
deferred.notify(1);
deferred.resolve();
}
};
addChain();
return deferred.promise;
}
};
}
})();
(function() {
'use strict';
angular
.module('App')
.controller('DemoController', DemoController);
DemoController.$inject = ['Async', '$q'];
function DemoController(Async, $q) {
var incrementNumber = function(item){
return $q.when(item.number++);
};
var numbers = [{ number: 1 }, { number: 2 }, { number: 3 }];
Async.mapSeries(numbers, function(item, index, length){
return incrementNumber(item);
}).then(function(res){
console.log(numbers);
alert("Cool!");
}, function(err){
alert(err);
}, function(percentage){
console.log(percentage);
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment