Last active
June 8, 2021 00:48
-
-
Save jdnichollsc/89aa64bffda68312ecfd3acd6294f1cc to your computer and use it in GitHub Desktop.
Angular mapSeries like Bluebird.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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; | |
} | |
}; | |
} | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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