Created
November 29, 2017 21:49
-
-
Save Harshit369/3d92507dd939f1729127d6f2e6346b4d to your computer and use it in GitHub Desktop.
Angular module/service for request queuing.
This file contains hidden or 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
| /** | |
| * Reuest queue service | |
| * USAGE: | |
| * Normal: return api.get(uri, { params: args }); | |
| * With requestQueue: return requestsQueue.queueRequest(function () { | |
| return api.get(uri, { params: args }); //this should return promise | |
| }); | |
| */ | |
| var module = ng.module('moduleName'); | |
| /** | |
| * Service to handle multiple simultanious api requests | |
| */ | |
| function requestsQueue() { | |
| /** | |
| * Initializes default options with max simultanious request limit set to : 3 | |
| * @type {Object} | |
| */ | |
| var requests = { | |
| queue: [], | |
| count: 0, | |
| maxCount: 3 | |
| }; | |
| /** | |
| * method that takes options object to overwrite default options | |
| * --currently overwrites maxcount only | |
| * @param {[type]} options [description] | |
| * @return {promise} [return a new promise object which resolves/rejects when original | |
| * promise returned by ayncfn resolves/rejects ] | |
| */ | |
| this.setOptions = function (options) { | |
| _.extend(requests, { maxCount: options.maxCount }); | |
| }; | |
| /** (IMPORTANT:: asyncFn should return promise) | |
| * main queueRequest method to call | |
| * @param {function} asyncFn [method to be executed when its turn comes] | |
| * @return {[type]} [description] | |
| */ | |
| this.queueRequest = function (asyncFn) { | |
| var processNext = function () { | |
| var index = _.findIndex(requests.queue, function (o) { | |
| return o.sent === false; | |
| }); | |
| if (index > -1) { | |
| var obj = requests.queue[index]; | |
| obj.sent = true; | |
| obj.originalFn().then(function (res) { | |
| obj.resolve(res); | |
| requests.count -= 1; | |
| processNext(); | |
| }).catch(function (err) { | |
| obj.reject(err); | |
| requests.count -= 1; | |
| processNext(); | |
| }); | |
| } | |
| }; | |
| var pObj = { | |
| sent: false, | |
| originalFn: asyncFn | |
| }; | |
| pObj.promise = new Promise(function (resolve, reject) { | |
| pObj.resolve = resolve; | |
| pObj.reject = reject; | |
| }); | |
| requests.queue.push(pObj); | |
| requests.count += 1; | |
| if (requests.count <= requests.maxCount) { | |
| processNext(); | |
| } | |
| return pObj.promise; | |
| }; | |
| } | |
| module.service('requestsQueue', requestsQueue); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment