Skip to content

Instantly share code, notes, and snippets.

@DForshner
Last active May 7, 2018 05:20
Show Gist options
  • Save DForshner/7312146 to your computer and use it in GitHub Desktop.
Save DForshner/7312146 to your computer and use it in GitHub Desktop.
jQuery - Parallel and Sequential Promises
ul {
list-style-type: disc;
margin:0 0 0 2em;
}
li {
margin:0 0 .5em;
}
body {
font-family: "Verdana";
font-size: 9pt;
}
header {
padding: 15px;
background-color: rgb(0, 175, 0);
color: #111;
}
header h1 {
font-size: 24pt;
}
article {
width: 80%;
margin: auto;
margin-top: 20px;
}
button{
padding: 5px;
}
<header>
<title>Parallel and Sequential Promises</title>
</header>
<body>
<header>
<h1>Parallel and Sequential Promises</h1>
</header>
<article>
A promise is an object that represents a future outcome that will eventually either be resolved(success) or rejected(failure). Once a promise reaches one of these states it will remain in that state forever and the callbacks will not fire again. A deferred object is like a promise with methods that allow us to resolve or reject it.
</article>
<article>
Parallel:
<button id="executeInParallel">Execute in parallel</button>
<button id="executeInParallelFaulty">Execute in parallel (faulty)</button>
</article>
<article>
Sequential:
<button id="executeInSequence">Execute in sequence</button>
<button id="executeInSequenceFaulty">Execute in sequence (faulty)</button>
</article>
<hr>
<article>
<ul id="log"></ul>
</article>
</body>
// Note: Requires jQuery 1.8+ to work properly.
var $ul = $('ul');
function msg(text) {
$ul.append('<li>' + text + '</li>');
}
function asyncTask1(input) {
input = input || "";
var dfd = $.Deferred(); // A Deferred is just a Promise with methods that allow its owner to resolve or reject it.
setTimeout(function () {
msg('asyncTask1 complete.');
dfd.resolve(input + 'A');
}, 2000);
return dfd.promise();
}
function asyncTask2(input) {
input = input || "";
var dfd = $.Deferred();
setTimeout(function () {
msg('asyncTask2 complete.');
dfd.resolve(input + 'B');
}, 1500);
return dfd.promise();
}
function faultyTask(input) {
input = input || "";
var deferred = $.Deferred();
setTimeout(function () {
msg('Simulating problem.');
try {
throw {
message: "Big Exception"
};
} catch (ex) {
deferred.reject(ex.message);
}
}, 1500);
return deferred.promise();
}
function asyncTask3(input) {
input = input || "";
var dfd = $.Deferred();
setTimeout(function () {
msg('asyncTask3 complete');
dfd.resolve(input + 'C');
}, 1000);
return dfd.promise();
}
function testParallel(simulateFaultyTask) {
console.assert(typeof simulateFaultyTask === 'boolean');
msg('Attempting to complete 3 aysnc tasks in parallel.');
var taskToUse;
if (simulateFaultyTask) taskToUse = faultyTask;
else taskToUse = asyncTask2;
// .when is used for waiting for multiple unordered events to occur.
$.when(asyncTask1(), taskToUse(), asyncTask3()).done(
function (result1, result2, result3) {
msg('All tasks complete: ', result1 + ', ' + result2 + ', ' + result3);
}).fail(
function (error) {
msg("One of the three tasks has failed" + error);
});
}
function testChainOfPromises(simulateFaultyTask) {
console.assert(typeof simulateFaultyTask === 'boolean');
msg('Attempting to complete 3 aysnc tasks in sequential order.');
var taskToUse;
if (simulateFaultyTask) taskToUse = faultyTask;
else taskToUse = asyncTask2;
// .then is used for sequences of events that happen in order.
asyncTask1().then(
function (result) {
msg("Step 1 complete: " + result);
return taskToUse(result);
},
function (error) {
msg("Step 1 failed: " + error);
return error;
}).then(
function (result) {
msg("Step 2 complete: " + result);
return asyncTask3(result);
},
function (error) {
msg("Step 2 failed: " + error);
return error;
}).then(
function (result) {
msg("Step 3 complete: " + result);
},
// When a Promise gets rejected it will immediately cascade down the then() chain so
// you can handle it at the end unless you want to handle it differently
// depending on the step that failed.
function (error) {
msg("Step 3 failed: " + error);
});
}
window.onload = function () {
$("#executeInParallel").click(function () {
testParallel(false);
});
$("#executeInParallelFaulty").click(function () {
testParallel(true);
});
$("#executeInSequence").click(function () {
testChainOfPromises(false);
});
$("#executeInSequenceFaulty").click(function () {
testChainOfPromises(true);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment