Skip to content
This repository has been archived by the owner on Sep 6, 2021. It is now read-only.

Commit

Permalink
Merge pull request #1009 from jhatwich/jhatwich/asyncAsync
Browse files Browse the repository at this point in the history
Add Async utility for background processing
  • Loading branch information
peterflynn committed Jul 27, 2012
2 parents a2e9807 + 6980cd4 commit e763215
Showing 1 changed file with 43 additions and 3 deletions.
46 changes: 43 additions & 3 deletions src/utils/Async.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,16 +157,16 @@ define(function (require, exports, module) {
*
* To perform task-specific work after an individual task completes, attach handlers to each
* Promise before beginProcessItem() returns it.
*
*
* @param {!Array.<*>} items
* @param {!function(*, number):Promise} beginProcessItem
* @param {!boolean} failAndStopFast
* @return {$.Promise}
*/
function doSequentially(items, beginProcessItem, failAndStopFast) {

var masterDeferred = new $.Deferred();
var hasFailed = false;
var masterDeferred = new $.Deferred(),
hasFailed = false;

function doItem(i) {
if (i >= items.length) {
Expand Down Expand Up @@ -199,6 +199,45 @@ define(function (require, exports, module) {
return masterDeferred.promise();
}

/**
* Executes a series of tasks sequentially in time-slices less than maxBlockingTime.
* Processing yields by idleTime between time-slices.
*
* @param {!Array.<*>} items
* @param {!function(*, number):Promise} fnProcessItem
* @param {!number} maxBlockingTime
* @param {!number} idleTime
* @return {$.Promise}
*/
function doSequentiallyInBackground(items, fnProcessItem, maxBlockingTime, idleTime) {

maxBlockingTime = maxBlockingTime || 15;
idleTime = idleTime || 30;

var sliceStartTime = (new Date()).getTime();

return doSequentially(items, function (item, i) {
var result = new $.Deferred();

// process the next item
fnProcessItem(item, i);

// if we've exhausted our maxBlockingTime
if ((new Date()).getTime() - sliceStartTime >= maxBlockingTime) {
//yield
window.setTimeout(function () {
sliceStartTime = (new Date()).getTime();
result.resolve();
}, idleTime);
} else {
//continue processing
result.resolve();
}

return result;
}, false);
}


/**
* Executes a series of tasks in parallel, saving up error info from any that fail along the way.
Expand Down Expand Up @@ -281,6 +320,7 @@ define(function (require, exports, module) {
// Define public API
exports.doInParallel = doInParallel;
exports.doSequentially = doSequentially;
exports.doSequentiallyInBackground = doSequentiallyInBackground;
exports.doInParallel_aggregateErrors = doInParallel_aggregateErrors;
exports.withTimeout = withTimeout;
exports.ERROR_TIMEOUT = ERROR_TIMEOUT;
Expand Down

0 comments on commit e763215

Please sign in to comment.