Skip to content

Simple promisify with sane defaults, works on node 0.10 if you provide custom Promise through options

License

Notifications You must be signed in to change notification settings

hybridables/redolent

Repository files navigation

redolent NPM version mit license NPM monthly downloads npm total downloads

Simple promisify with sane defaults, works on node 0.10 if you provide custom Promise through options

code climate code style linux build windows build code coverage dependency status paypal donate

You might also be interested in always-done.

Table of Contents

(TOC generated by verb using markdown-toc)

Install

Install with npm

$ npm install redolent --save

or install using yarn

$ yarn add redolent

Usage

For more use-cases see the tests

const redolent = require('redolent')

API

Will try to promisify fn with native Promise, otherwise you can give different promise module to opts.Promise, for example pinkie or bluebird. If fn is-async-function it will be passed with done callback as last argument - always concatenated with the other provided args through opts.args.

Note: Uses native-or-another for detection, so it will always will use the native Promise, otherwise will try to load some of the common promise libraries and as last resort if can't find one of them installed, then throws an Error!

Params

  • <fn> {Function}: a function to be promisified
  • [opts] {Object}: optional options, also passed to native-or-another
  • [opts.args] {Array}: additional arguments to be passed to fn, all args from opts.args and these that are passed to promisifed function are concatenated
  • [opts.context] {Object}: what context to be applied to fn, by default it is smart enough and applies the this context of redolent call or the call of the promisified function
  • [opts.Promise] {Function}: custom Promise constructor for versions < v0.12, like bluebird for example, by default it always uses the native Promise in newer node versions
  • [opts.global] {Boolean}: defaults to true, pass false if you don't want to attach/add/register the given promise to the global scope, when node < v0.12
  • returns {Function}: promisified function

Example

const fs = require('fs')
const request = require('request')
const redolent = require('redolent')

redolent(fs.readFile)('package.json', 'utf-8').then(data => {
  console.log(JSON.parse(data).name)
})

// handles multiple arguments by default
redolent(request)('http://www.tunnckocore.tk/').then(result => {
  const [httpResponse, body] = result
})

// `a` and `b` arguments comes from `opts.args`
// `c` and `d` comes from the call of the promisified function
const fn = redolent((a, b, c, d, done) => {
  console.log(typeof done) // => 'function'
  done(null, a + b + c + d)
}, {
  args: [1, 2]
})

fn(3, 5).then((res) => {
  console.log(res) // => 11
})

Tip: You can use require('native-or-another/register') instead of passing a promise to opts.Promise, it exposes a function that accepts same options object, { Promise: MyPromise } for example.

Detecting Promise

For testing and such purposes you may want to detect which promise is used. Because of that the returned promise has promise.___nativePromise which will be true if native Promise is available on the environment or promise.___customPromise === true if custom Promise constructor is passed through opts.Promise

const fs = require('fs')
const redolent = require('redolent')

// use Bluebird Promise
const readFile = redolent(fs.readFile, {
  Promise: require('bluebird')
})

const promise = readFile('package.json', 'utf-8').then(data => {
  console.log(JSON.parse(data).name)
})

console.log(promise.___customPromise) // => true
console.log(promise.___nativePromise) // => false

Related

  • always-done: Handle completion and errors with elegance! Support for streams, callbacks, promises, child processes, async/await and sync functions. A drop-in replacement… more | homepage
  • always-promise: Promisify, basically, everything. Generator function, callback-style or synchronous function; sync function that returns child process, stream or observable; directly passed… more | homepage
  • always-thunk: Create thunk from async or sync function. Works like thunkify. | homepage
  • arr-includes: Return positive value if any of passed values exists in array, or optionally an index. | homepage
  • dush: Microscopic & functional event emitter in ~260 bytes, extensible through plugins. | homepage
  • letta: Promisify sync, async or generator function, using relike. Kind of promisify, but lower level. Full compatibility with co4 and passing… more | homepage
  • minibase: Minimalist alternative for Base. Build complex APIs with small units called plugins. Works well with most of the already existing… more | homepage
  • native-promise: Get native Promise or falsey value if not available. | homepage
  • relike-value: Create promise from sync, async, string, number, array and so on. Handle completion (results) and errors gracefully! Built on top… more | homepage
  • try-catch-core: Low-level package to handle completion and errors of sync or asynchronous functions, using once and dezalgo libs. Useful for and… more | homepage

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Please read the contributing guidelines for advice on opening issues, pull requests, and coding standards.
If you need some help and can spent some cash, feel free to contact me at CodeMentor.io too.

In short: If you want to contribute to that project, please follow these things

  1. Please DO NOT edit README.md, CHANGELOG.md and .verb.md files. See "Building docs" section.
  2. Ensure anything is okey by installing the dependencies and run the tests. See "Running tests" section.
  3. Always use npm run commit to commit changes instead of git commit, because it is interactive and user-friendly. It uses commitizen behind the scenes, which follows Conventional Changelog idealogy.
  4. Do NOT bump the version in package.json. For that we use npm run release, which is standard-version and follows Conventional Changelog idealogy.

Thanks a lot! :)

Building docs

Documentation and that readme is generated using verb-generate-readme, which is a verb generator, so you need to install both of them and then run verb command like that

$ npm install verbose/verb#dev verb-generate-readme --global && verb

Please don't edit the README directly. Any changes to the readme must be made in .verb.md.

Running tests

Clone repository and run the following in that cloned directory

$ npm install && npm test

Author

Charlike Mike Reagent

License

Copyright © 2015, 2017, Charlike Mike Reagent. Released under the MIT License.


This file was generated by verb-generate-readme, v0.4.3, on March 19, 2017.
Project scaffolded using charlike cli.