Skip to content

Instantly share code, notes, and snippets.

@dlidstrom
Last active January 16, 2017 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlidstrom/5773155 to your computer and use it in GitHub Desktop.
Save dlidstrom/5773155 to your computer and use it in GitHub Desktop.
Command buffer service for AngularJS used to manage asynchronous calls in a synchronized fashion.
/**
* This service is used to serialize asynchronous events.
* It uses a buffering solution: http://ricostacruz.com/backbone-patterns/animation-buffer.html
* To use it, put your asynchronous actions (animations/ajax) inside an anonymous function
* to be passed into add().
* Be sure to trigger next() when done.
*
* Example:
* commandBuffer.add(next => {
* somePromise.done(next);
* });
*/
var commands = [];
const next = () => {
commands.shift();
if (commands.length) {
commands[0](next);
}
};
/**
* Add a function to the command buffer.
* @param {fn} Function to execute.
*/
const add = fn => {
commands.push(fn);
if (commands.length == 1) {
fn(next);
}
};
/**
* Add a function to the command buffer, prioritized.
* This means the function will execute next.
* @param {fn} Function to execute.
*/
const addFirst = fn => {
if (commands.length) {
commands.splice(1, 0, fn);
}
else {
commands.unshift(fn);
}
if (commands.length == 1) {
fn(next);
}
};
export default {
add,
addFirst
};
(function (app) {
'use strict';
/**
* This service is used to serialize asynchronous events.
* It uses a buffering solution: http://ricostacruz.com/backbone-patterns/animation-buffer.html
* To use this, put your animations inside an anonymous function to be passed onto add().
* Be sure to trigger next() when the animations are done.
*
* Example:
* CommandBuffer.add(function (next) {
* somePromise.done(function () { next(); });
* };
*/
app.factory('CommandBuffer', function () {
var commands = [];
var next = function () {
commands.shift();
if (commands.length) commands[0](next);
};
return {
/**
* Add a function to the command buffer.
* @param {fn} Function to execute.
*/
add: function (fn) {
commands.push(fn);
if (commands.length == 1) fn(next);
},
/**
* Add a function to the command buffer, prioritized.
* This means the function will execute next.
* @param {fn} Function to execute.
*/
addFirst: function (fn) {
if (commands.length)
commands.splice(1, 0, fn);
else
commands.unshift(fn);
if (commands.length == 1) fn(next);
}
};
});
})(window.App);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment