Skip to content

Instantly share code, notes, and snippets.

@tcrowe
Created February 1, 2020 20:12
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 tcrowe/9ad715c83a95a93c6eabc622a8758a48 to your computer and use it in GitHub Desktop.
Save tcrowe/9ad715c83a95a93c6eabc622a8758a48 to your computer and use it in GitHub Desktop.
Turn async await into tuple output
/**
* 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/
@tcrowe
Copy link
Author

tcrowe commented Feb 1, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment