Created
January 24, 2012 18:19
-
-
Save fpillet/1671671 to your computer and use it in GitHub Desktop.
Ordered processing of CF.request() results for CommandFusion iViewer
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
/* OrderedRequestQueue.js | |
* | |
* Push CF.request calls using this object instead of directly using CF.request, and | |
* you'll be guaranteed to receive results in the order you pushed them. Note that this | |
* implies that the queue will BLOCK until each result is received in sequence, which may | |
* cause large delays if one site in the list is long to respond. | |
* | |
* Use at your own risk | |
*/ | |
var OrderedRequestQueue = (function(){ | |
var self = { | |
q: [], | |
nextDequeue: 0, | |
nextEnqueue: 0 | |
}; | |
self.addRequest = function(url, method, headers, body, callbackFunction) { | |
var reqid = self.nextEnqueue++; | |
self.q[reqid] = { callback: callbackFunction }; | |
CF.request(url, method, headers, body, function(status, resHeader, resBody) { | |
self.q[reqid].result = [status, resHeader, resBody]; | |
processResultQueue(); | |
}); | |
}; | |
function processResultQueue() { | |
while (self.nextDequeue < self.nextEnqueue) { | |
var entry = self.q[self.nextDequeue]; | |
if (entry !== undefined) { // has been manually removed from queue? | |
if (entry.result === undefined) { | |
break; // result not yet received, block queue processing | |
} | |
if (entry.callback != null) { | |
try { | |
entry.callback.apply(null, entry.result); | |
} catch (e) { | |
CF.log("Exception catched while calling CF.request callback: " + e); | |
} | |
} | |
delete self.q[self.nextDequeue]; | |
} | |
self.nextDequeue++; | |
} | |
} | |
return self; | |
})(); | |
/* Example use: | |
* | |
* OrderedRequestQueue.addRequest(url,"GET",{},"body",function(status, headers, body) { | |
CF.log("Got result " + body + " (status " + status + ")"); | |
}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment