Skip to content

Instantly share code, notes, and snippets.

@tcrowe
Created February 1, 2020 20:20

Revisions

  1. tcrowe created this gist Feb 1, 2020.
    39 changes: 39 additions & 0 deletions object-ification-of-promise.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@

    /**
    * 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/