Created
February 1, 2020 20:12
-
-
Save tcrowe/9ad715c83a95a93c6eabc622a8758a48 to your computer and use it in GitHub Desktop.
Turn async await into tuple output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Tuple-ification of a promise result | |
* @method to | |
* @param {promise} p | |
* @returns {array} | |
*/ | |
const to = p => p.then(res => [null, res]).catch(err => [err]); | |
/** | |
* Test success promise | |
* @returns {promise} | |
*/ | |
const test1 = async () => "ok"; | |
/** | |
* Test fail promise | |
* @returns {promise} | |
*/ | |
const test2 = async () => { throw new Error("not ok =["); }; | |
async function start() { | |
// 💰 | |
const [ err, res ] = await to(test1()); | |
console.log("err", err) // null | |
console.log("res", res) // "ok" | |
const [ err2, res2 ] = await to(test2()); | |
// 💰 | |
console.log("err2", err2) // Error: not ok | |
console.log("res2", res2) // undefined | |
} | |
console.log(start()); // Promise { <pending> } | |
// more reading | |
// https://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Object version https://gist.github.com/tcrowe/d025922d56d25dbd4ec89fb966387f4d