1.0.17 • Published 5 years ago

js-promesify v1.0.17

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

JS Promesify

With promesify you can easily convert any Node callback based function to a promise

Example

Given any callback based function, e.g.:

export const asyncRandom = (min: number, max: number, cb: (err, res) => any) => {
  setTimeout(() => {
    if (Math.random() > 0.7) {
      return cb("A rare exception ocurred", null);
    }
    return cb(null, Math.floor(Math.random() * (max - min) + min))
  }, 1000);
}

Let's say i want to consume the asyncRandom function to generate a min random value, a max random value, and then a value between those min and max. It could look like this:

app.get('/cb', (req, res) => {
  asyncRandom(1, 10, (err, min) => {
    if (err) {
      return res.status(500).json({ err: err })
    }
    asyncRandom(80, 90, (err, max) => {
      if (err) {
        return res.status(500).json({ err: err })
      }
      asyncRandom(min, max, (err, num) => {
        if (err) {
          return res.status(500).json({ err: err })
        }
        return res.json({
          number: num
        })
      })
    })
  })
});

With promesifyjs that code would be much more cleaner.

app.get('/promise', async (req, res) => {
    try {
        let min = await Promesify<number>(asyncRandom, 1, 10);
        let max = await Promesify<number>(asyncRandom, 80, 90);
        let num = await Promesify<number>(asyncRandom, min, max);
        return res.json({
            number: num
        });
    } catch (ex) {
        return res.status(500).json({
            err: ex
        });
    }
});

Installation

npm i -s js-promesify

Usage

import { Promesify } from "js-promesify";
1.0.17

5 years ago

1.0.16

5 years ago

1.0.15

5 years ago

1.0.14

5 years ago

1.0.13

5 years ago

1.0.12

5 years ago

1.0.11

5 years ago

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago