Skip to content
/ unthen Public

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

License

Notifications You must be signed in to change notification settings

astur/unthen

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

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

Resources

License

Stars

Watchers

Forks

Packages

No packages published