Last active
August 29, 2015 14:02
-
-
Save hatyuki/e38cea809a86ca725602 to your computer and use it in GitHub Desktop.
AngularJS で Semaphore してみたい
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
'use strict'; | |
angular.module('myApp', [ | |
'ngResource', | |
'ngSemaphore' | |
]).config(function ($provide) { | |
$provide.value('SemaphoreConfig', { | |
parallels: 5 | |
}); | |
}).controller( | |
'MainCtrl', function ($scope, $resouce, Semaphore) { | |
$scope.getApiData = function (url) { | |
Semaphore.down(function (sem) { // Semaphore が down( ) できなければ Queue に入る | |
$resource(url).get( ).then(function (response) { | |
// ... | |
sem.up( ); // 最後に Semaphore を up( ) する | |
}); | |
}); | |
}; | |
}); |
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
'use strict'; | |
angular.module('myApp').factory( | |
'Semaphore', function ($q, SemaphoreConfig) { | |
var klass = { | |
parallels: SemaphoreConfig.parallels || 5, | |
queues: [ ] | |
}; | |
klass.remain = klass.parallels; | |
klass.down = function (callback, context) { | |
var deferred = $q.defer( ); | |
var semaphore = new SemaphoreInstance(deferred); | |
if (klass.remain == 0) { | |
klass.queues.push({ | |
callback: callback, | |
context: context | |
}); | |
} else { | |
--klass.remain; | |
callback.call(context, semaphore); | |
} | |
}; | |
var onSemaphoreUp = function ( ) { | |
var queue = klass.queues.shift( ); | |
if (queue) { | |
klass.down(queue.callback, queue.context); | |
}; | |
}; | |
var SemaphoreInstance = function (deferred) { | |
this.deferred = deferred; | |
this.deferred.promise.then(onSemaphoreUp); | |
}; | |
SemaphoreInstance.prototype.up = function ( ) { | |
if (klass.remain >= klass.parallels) { | |
this.deferred.reject( ); | |
} else { | |
++klass.remain; | |
this.deferred.resolve( ); | |
} | |
}; | |
return klass; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment