Skip to content

joelnet/functional-helpers

Repository files navigation

functional-helpers GitHub license travis-ci build image GitHub license

Functional JavaScript Helpers

DEPRECATED

This project has been deprecated and is no longer in development. All future work will be done on MojiScript

Installation

npm install --save joelnet/functional-helpers

Or if you want a specific version

npm install --save joelnet/functional-helpers#1.4.0

API Reference

Functions

callbackify(promise, [context])function

Converts a promise-returning function into a node-sytle callback function.

promisify(func, [context])function

Converts a node-style callback function into a promise-returning function.

promisifyAll(obj)Object

Converts all functions in an object from node-style callbacks to promise-returning functions. Does not modify the original function and instead returns a new object.

callbackify(promise, [context]) ⇒ function

Converts a promise-returning function into a node-sytle callback function.

Kind: global function
Returns: function - A node-style callback function.

Param Type Description
promise function A promise-returning function.
[context] Object The context to assign to this.

Example

import callbackify from 'functional-helpers/callbackify'

const callback = callbackify((x, y) => Promise.resolve(x + y))

callback(2, 3, (err, data) => {
  if (err) return console.log('Unknown error', err)
  console.log('result = ', data)
})

promisify(func, [context]) ⇒ function

Converts a node-style callback function into a promise-returning function.

Kind: global function
Returns: function - A function that will return a promise.

Param Type Description
func function Node style callback function to convert.
[context] Object The context to assign to this.

Example

import promisify from 'functional-helpers/promisify'

const readFile = promisify(fs.readFile)

// works as a promise
readFile('file.txt', 'utf8')
  .then(file => console.log(file))
  .catch(err => console.log('error reading file', err))

// also works as a callback
readFile('file.txt', 'utf8', (err, file) => {
  if (err) return console.log('error reading file', err))
  console.log(file)
})

promisifyAll(obj) ⇒ Object

Converts all functions in an object from node-style callbacks to promise-returning functions. Does not modify the original function and instead returns a new object.

Kind: global function
Returns: Object - Object with all functions promisified.

Param Type Description
obj Object Object to promisify.

Example

import promisifyAll from 'functional-helpers/promisifyAll'
import fs from 'fs'

const fsp = promisifyAll(fs)

// works as a promise
fsp.readFile('file.txt', 'utf8')
  .then(file => console.log(file))
  .catch(err => console.log('error reading file', err))

// also works as a callback
fsp.readFile('file.txt', 'utf8', (err, file) => {
  if (err) return console.log('error reading file', err)
  console.log(file)
})

License

Unlicense