Skip to content

Instantly share code, notes, and snippets.

@amackintosh
Last active June 14, 2017 18:32
Show Gist options
  • Save amackintosh/22ac8b8b87184fc965091ef2830d902d to your computer and use it in GitHub Desktop.
Save amackintosh/22ac8b8b87184fc965091ef2830d902d to your computer and use it in GitHub Desktop.
Promise & Async/Await Demo
// Async function that checks input for no reason
// and then resolves or rejects the promise depending on the input
async function asyncWin(string) {
var input = string;
// Private helper method that displays pointless message
function _pointless() {
console.log('We just waited 1.337 seconds for no reason.')
};
// Invoke helper method after 1.337 seconds and wait until it is done
var ok = await new Promise((resolve, reject) => {
setTimeout(() => { resolve(_pointless()); }, 1337);
});
// When ready, resolve or reject the promise
return new Promise((resolve, reject) => {
if (input) {
if (input.length > 5) {
resolve('input is greater than 5 characters: ' + input);
} else if (input.length === 5){
resolve('input is 5 characters: ' + input);
} else {
reject('input is less than 5 characters: ' + input);
};
} else {
reject('no input');
};
});
};
// Run the async function with proper handling
// .then() fires if resolved
// .catch() fires if rejected
asyncWin()
.then(x => { console.log('Resolved: ' + x); })
.catch(err => { console.log('Rejected: ' + err); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment