Created
July 30, 2013 20:28
-
-
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.
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
| // 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)); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks Max, really useful!