Skip to content

Instantly share code, notes, and snippets.

@hiroaki
Last active December 18, 2016 05:31
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 hiroaki/da2053fda5162a3298a7ce8111942e77 to your computer and use it in GitHub Desktop.
Save hiroaki/da2053fda5162a3298a7ce8111942e77 to your computer and use it in GitHub Desktop.
invoke callbacks that contain async confirmation
<html><head><title>Promise</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script>
$(function() {
$('#start').show();
$('#prepare').hide();
$('#dialog').hide();
$('#contents').hide();
$('#goal').hide();
var callbacks = [];
// (1)
callbacks.push(function(input_value){
$('#prepare').show();
if ( input_value == 1 ) {
return false;
}
});
// (2)
callbacks.push(function(input_value) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('dialog opens');
$('#dialog').show();
$('#dialog input[name=ok]').on('click', function() {
$('#dialog input').remove();
resolve();
});
$('#dialog input[name=cancel]').on('click', function() {
$('#dialog input').remove();
reject();
});
}, 0 );
})
});
// (3)
callbacks.push(function(input_value){
$('#contents').show();
if ( input_value == 2 ) {
return false;
}
});
// start
$('#start input[name=go]').on('click', function() {
var input_value = $(this).data('value'),
promises;
promises = callbacks.map(function(cb) {
return function() {
var return_value = cb.call(null, input_value);
if ( return_value && return_value.then instanceof Function ) {
return return_value;
} else {
if ( return_value === false ) {
return Promise.reject();
} else {
return Promise.resolve();
}
}
};
});
console.log('go into reduce');
promises.reduce(function(prev, curr) {
return prev.then(curr); // "then" returns a Promise
}, Promise.resolve(null))
.then(function(){
$('#goal').show();
})
.catch(function() {
$('#goal').empty().append('<h2>CANCELED!</h2>').show();
});
});
});
</script>
</head>
<body>
<div id="start">
<h2>Start</h2>
<div>
<input type="button" name="go" value="success story" data-value="0">
<input type="button" name="go" value="fail at #1" data-value="1">
<input type="button" name="go" value="fail at #2" data-value="2">
</div>
</div>
<hr>
<div id="prepare">
<h2>Prepare</h2>
</div>
<hr>
<div id="dialog">
<h2>Confirm</h2>
<div>
<input type="button" name="ok" value="ok">
<input type="button" name="cancel" value="cancel">
</div>
</div>
<hr>
<div id="contents">
<h2>Contents</h2>
</div>
<hr>
<div id="goal">
<h2>Goal</h2>
</div>
<hr>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment