unthen

    1.0.1 • Public • Published

    unthen

    Convert anything to Promise that resolves to [err, res] array

    Build Status NPM version

    Install

    npm i unthen

    Usage

    const unthen = require('unthen');
     
    (async function(){
        console.log(await unthen(1));                           //resolves to [null, 1]
        console.log(await unthen(new Error()));                 //resolves to [Error: ]
        console.log(await unthen(Promise.resolve(1)));          //resolves to [null, 1]
        console.log(await unthen(Promise.reject(new Error()))); //resolves to [Error: ]
    })()

    Why?..

    Just because [err, res] way is more familiar for many of us, even in promise epoch.

    Classic way (from this article):

    async function handler (req, res) {
        let response
        try {
            response = await request('https://user-handler-service')  
        } catch (err) {
            logger.error('Http error', err)
            return res.status(500).send()
        }
     
        let document
        try {
            document = await Mongo.findOne({ user: response.body.user })
        } catch (err) {
            logger.error('Mongo error', err)
            return res.status(500).send()
        }
     
        executeLogic(document, req, res)
    }

    New way with unthen:

    const U = require('unthen');
    async function handler (req, res) {
        const [httpErr, response] = await U(request('https://user-handler-service'))
        if (httpErr) {
            logger.error('Http error', err)
            return res.status(500).send()
        }
     
        const [mongoErr, document] = await U(Mongo.findOne({ user: response.body.user }))
        if(mongoErr) {
            logger.error('Mongo error', err)
            return res.status(500).send()
        }
     
        executeLogic(document, req, res)
    }

    License

    MIT

    Install

    npm i unthen

    DownloadsWeekly Downloads

    2

    Version

    1.0.1

    License

    MIT

    Unpacked Size

    4.87 kB

    Total Files

    8

    Last publish

    Collaborators

    • avatar