Skip to content

Instantly share code, notes, and snippets.

@Klortho
Last active May 4, 2017 19:49
Show Gist options
  • Save Klortho/ecbfd5405d0d0a4bb464423ffbe2a972 to your computer and use it in GitHub Desktop.
Save Klortho/ecbfd5405d0d0a4bb464423ffbe2a972 to your computer and use it in GitHub Desktop.
Chaining conditional jQuery promises
<html>
<head>
<style>
#log {
background: black;
color: #AFA;
font-size: 90%;
margin: 1em;
padding: 0.7em;
}
</style>
</head>
<body>
<p>
Demonstrate chaining conditional jQuery promises.
</p>
<pre id='log'></pre>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js'></script>
<script>
var logElem = document.getElementById('log');
function log(msg) {
var txt = document.createTextNode(msg + '\n');
logElem.appendChild(txt);
}
var myLoc = window.location.pathname;
var myDir = myLoc.substring(0, myLoc.lastIndexOf('/'));
function getSwitcher(cond) {
log('Testing conditional promise with condition == ' + cond);
// get the parameter to use for the final ajax call from either an
// initial ajax call (if cond == true) or from a syncronous source.
preload = cond ?
$.get(myDir + '/ajax-1.txt').then(function(res) { return res; }) :
$.Deferred().resolve('constant-1');
// this will fetch, via ajax, one of two files
preload
.then(function(x) {
return $.get(myDir + '/ajax-2-' + x + '.txt');
})
.then(function(resp) {
log('... for cond == ' + cond + ', the final response: ' + resp);
});
}
[true, false].forEach(getSwitcher);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment