0.1.0 • Published 2 years ago

promi v0.1.0

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

Promi

This module's only purpose is to convert classic callback style to a promised one. So, instead of doing this:

  fs.readFile('myFile.txt', 'utf8', function (err, result) {
    if (err) console.log(err)
    // do something useful
  })

You can do this:

const content = await readFile('myFile.txt', 'utf8')

// or handle errors with classic try/catch
try {
  const content = await readFile('myFile.txt', 'utf8')
} catch (err) {
  console.log(err)
}

There are tons of other/better more mature implementations out there but I felt like implementing my own for recreational purposes only.

It is literally only 6 lines of code counting line breaks, so no performance penalties here.

// You can use promi() to create a wrapped function that returns a promise like this:
promi(fn) // => function(...args) => Promise

// or you can use promi.now() to directly create a promise if you don't want to cache the wrapper
promi.now(fn, ...args) // => Promise

// so you can do
const content = await promi.now(fs.readFile, 'myFile.txt', 'utf8')

Example

'use strict'

const fs = require('fs')
const promi = require('promi')

const readFile = promi(fs.readFile)

async function doSomething () {
  try {
    const content = await readFile('/myFile.txt', 'utf8')
    // ...
  } catch (err) {
    // handle error
  }
}