JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
<link rel="stylesheet" href="https://weblibrary.cdn.citrixonline.com/fonts/citrix-sans/citrixsans.css">
<h3>
Promise chaining:
</h3>
<p>
Since, then method returns a promise too, you can chain the promises.
</p>
<div id='tryButton' style='margin-top: 20px'>
<span>
<a class='btn btn-primary pull-left' href='#' role='button'>
<i class='fa fa-share' aria-hidden='true'></i>
Try
</a>
</span>
</div>
<p id='output'>
</p>
CSS
body {
padding: 20px;
}
#output {
padding: 50px;
}
JavaScript
function tryAPromiseChain() {
$('#output').empty();
function aToss() {
return Math.floor(Math.random() * 6) + 1;
};
function toss() {
return new Promise(function(fulfill, reject) {
var chance = aToss();
if (chance === 6) {
fulfill(chance);
} else {
reject('Ouch.');
}
})
};
function tossAgain(message) {
$('#output').append(message);
return toss();
};
function gotSix(chance) {
$('#output').append(chance + '. Yay!');
};
function neverGotSix(message) {
$('#output').append(message);
};
toss()
.then(null, tossAgain)
.then(null, tossAgain)
.then(gotSix, tossAgain);
}
$('#tryButton').click(tryAPromiseChain);