Skip to content

Instantly share code, notes, and snippets.

@igormukhin
Created September 19, 2016 13:18
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 igormukhin/203ca3a7ec5d3423f74500cfc0bb7bc5 to your computer and use it in GitHub Desktop.
Save igormukhin/203ca3a7ec5d3423f74500cfc0bb7bc5 to your computer and use it in GitHub Desktop.
Example of an ordered processing of asynchronous event handled by asynchronous handlers (JavaScript / jQuery, Promise).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<script>
/**
* Executes submitted jobs in order.
*
* Useful for async jobs. Async jobs should return a promise.
* After the promise is resolved, the next job will be executed.
*
* Use .submit(job) to add a new job.
*
* Example of a async job:
*
* executionChain.submit(function() {
* var deferred = $.Deferred();
* setTimeout(function () {
* console.log('Completed');
* deferred.resolve();
* }, 2000);
* return deferred.promise();
* });
*
* @returns {ExecutionChain}
* @constructor
*/
function ExecutionChain() {
var lastPromise = $.when();
this.submit = function (job) {
if (!$.isFunction(job)) {
throw "not a function: " + job;
}
lastPromise = lastPromise.then(job, job);
};
return this;
}
$(function () {
$('button[data-num]').on('click', function () {
var num = $(this).attr('data-num');
fire(num);
});
var chain = new ExecutionChain();
function fire(num) {
log('Fired ' + num);
var func = function () {
return handler(num);
};
if (num == 3) {
func = function () {
log('Sync handler 3 executed');
};
}
chain.submit(func);
}
function handler(num) {
var deferred = $.Deferred();
log('Started ' + num);
setTimeout(function () {
if (num == 4) {
log('Failed ' + num);
deferred.reject();
} else {
log('Completed ' + num);
deferred.resolve();
}
}, 2000);
return deferred.promise();
}
function log(msg) {
var $console = $('#console');
$console.val($console.val() + '\n' + msg);
}
});
</script>
<body>
<button data-num="1">Fire 1 async</button>
<button data-num="2">Fire 2 async</button>
<button data-num="3">Fire 3 sync</button>
<button data-num="4">Fire 4 fail</button>
<label>Console:</label>
<textarea id="console" style="width: 400px; height: 400px;"></textarea>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment