Skip to content

Instantly share code, notes, and snippets.

@maxpeterson
Created July 30, 2013 20:28
Show Gist options
  • Select an option

  • Save maxpeterson/6116613 to your computer and use it in GitHub Desktop.

Select an option

Save maxpeterson/6116613 to your computer and use it in GitHub Desktop.
Queue to ensure that functions are not called concurrently. Created to wrap Veeva API calls that can not be called concurrently.
// The Veeva API can only accept one call at a time.
// A queue is used to avoid calling the API while an earlier call is in progress.
var Queue = (function () {
var queue = [];
var empty = true;
return {
// Add a function to the queue
// (it will be called immediately if the queue is empty)
push: function (fn) {
queue.push(fn);
if (empty) {
empty = false;
this.next();
}
},
// Tell the queue to process the next item.
// To be called by callbacks of functions added to the queue.
next: function () {
fn = queue.pop();
if (fn) {
fn();
} else {
empty = true;
}
},
// Wrap a callback so it calls next after the callback completes.
wrap: function (callback) {
var next = this.next;
return function () {
var result = callback.apply(this, arguments);
next();
return result;
}
}
}
})();
// Calls to the underlying API can be wrapped so they use the queue.
function getDataForCurrentObjectQueued(object, field, callback) {
Queue.push(function () {
com.veeva.clm.getDataForCurrentObject(object, field, Queue.wrap(callback));
});
}
function createRecordQueued(object, values, callback) {
Queue.push(function () {
com.veeva.clm.createRecord(object, values, Queue.wrap(callback));
});
}
@AlexGach
Copy link

AlexGach commented Apr 3, 2014

Thanks Max, really useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment