Created
February 1, 2020 20:20
-
-
Save tcrowe/d025922d56d25dbd4ec89fb966387f4d to your computer and use it in GitHub Desktop.
Turn async await promise into object result
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
/** | |
* Object-ification of a promise result | |
* @method to | |
* @param {promise} p | |
* @returns {array} | |
*/ | |
const to = p => | |
p.then(res => ({ err: 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() { | |
// 💰 | |
var { err, res } = await to(test1()); | |
console.log("err", err) // null | |
console.log("res", res) // "ok" | |
var { err, res } = await to(test2()); | |
// 💰 | |
console.log("err", err) // Error: not ok | |
console.log("res", res) // 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
Array version https://gist.github.com/tcrowe/9ad715c83a95a93c6eabc622a8758a48