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>
Promises (ES 6)
</h3>
<p>
A Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.
<aside>
<h4>
States
</h4>
<ul>
<li> Pending </li>
<li>
Fulfilled (with a value)
</li>
<li> Rejected (with a reason) </li>
</ul>
</aside>
</p>
<p>
<em> promise.then(onFulfilled, onRejected): </em> Returns a promise
</p>
<p>
<em> promise.catch(onRejected): </em> Returns a promise
</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>
<div id='output'>
</div>
CSS
body {
padding: 20px;
}
#output {
padding: 50px;
}
JavaScript
function tryAPromise() {
function aToss() {
return Math.floor(Math.random() * 6) + 1;
};
var toss = new Promise(function(fulfill, reject) {
var chance = aToss();
if (chance === 6) {
fulfill(chance);
} else {
reject('Let me give it another shot.');
}
});
toss.then(function(chance) {
$('#output').empty()
.append(chance + '. Yay, got my chance');
}, function(message) {
$('#output').empty()
.append(message);
});
}
$('#tryButton').click(tryAPromise);