Skip to content

Instantly share code, notes, and snippets.

@0xadada 0xadada/await-async.js
Last active Dec 3, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.