Skip to content

Instantly share code, notes, and snippets.

@0xadada
Last active December 3, 2017 22:34
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 0xadada/df21f66663e77a3306ac61b609c6ce57 to your computer and use it in GitHub Desktop.
Save 0xadada/df21f66663e77a3306ac61b609c6ce57 to your computer and use it in GitHub Desktop.
The Promise of await / async
// async / await
/**
* Resolve a truthy value, reject a falsy value.
* @param {any} value Any Javascript primative type.
* @param {Number} timeout Time n milliseconds before function returns.
* @returns {Promise} a Promise.
*/
let isTruthy = function(value, timeout) {
return new Promise((resolve, reject) => {
window.setTimeout(() => {
value = value ? true : false;
if(value === true) {
return resolve(value);
} else {
return reject(value);
}
}, timeout);
});
};
let getResult = async function(value) {
setTimeout(() => console.info(`${value} 2`), 2000);
setTimeout(() => console.info(`${value} 3`), 3000);
setTimeout(() => console.info(`${value} 1`), 1000);
try {
let result = await isTruthy(value, 3100);
console.info(`try result '${value}': ${result}`);
} catch(error) {
console.warn(`catch result: '${value}': ${error}`);
}
}
getResult('yes');
getResult(0);
/* Improvements:
* - Code is subjectively easier to reason about.
* - No need for `.then()` or `.catch()` in `getResult`.
* - getResult can use try / catch to handle Promise rejection errors in `isTruthy`
* - Debugging is easier, `.then` and `.catch` dont accept break-points as the
* body is an expression, not a function body.
*/
// Promises
/**
* Resolve a truthy value, reject a falsy value.
* @param {any} value Any Javascript primative type.
* @param {Number} timeout Time n milliseconds before function returns.
* @returns {Promise} a Promise.
*/
let isTruthy = function(value, timeout) {
return new Promise((resolve, reject) => {
window.setTimeout(() => {
value = value ? true : false;
if(value === true) {
return resolve(value);
} else {
return reject(value);
}
}, timeout);
});
};
let getResult = function(value) {
setTimeout(() => console.info(`${value} 2`), 2000);
setTimeout(() => console.info(`${value} 3`), 3000);
setTimeout(() => console.info(`${value} 1`), 1000);
let resultPromise = isTruthy(value, 3100);
resultPromise
.then(result => console.info(`then result '${value}': ${result}`))
.catch(result => console.warn(`catch result: '${value}': ${result}`));
}
getResult('yes');
getResult(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment