1. universalify
Make a callback- or promise-based function support both promises and callbacks.
universalify
Package: universalify
Created by: RyanZim
Last modified: Wed, 01 Nov 2023 17:12:45 GMT
Version: 2.0.1
License: MIT
Downloads: 316,404,432
Repository: https://github.com/RyanZim/universalify

Install

npm install universalify
yarn add universalify

universalify

GitHub Workflow Status (branch)
Coveralls github branch
npm
npm

Make a callback- or promise-based function support both promises and callbacks.

Uses the native promise implementation.

Installation

 npm install universalify

API

universalify.fromCallback(fn)

Takes a callback-based function to universalify, and returns the universalified function.

Function must take a callback as the last parameter that will be called with the signature (error, result). universalify does not support calling the callback with three or more arguments, and does not ensure that the callback is only called once.

 function callbackFn (n, cb) {
  setTimeout(() => cb(null, n), 15)
}

const fn = universalify.fromCallback(callbackFn)

// Works with Promises:
fn('Hello World!')
.then(result => console.log(result)) // -> Hello World!
.catch(error => console.error(error))

// Works with Callbacks:
fn('Hi!', (error, result) => {
  if (error) return console.error(error)
  console.log(result)
  // -> Hi!
})

universalify.fromPromise(fn)

Takes a promise-based function to universalify, and returns the universalified function.

Function must return a valid JS promise. universalify does not ensure that a valid promise is returned.

 function promiseFn (n) {
  return new Promise(resolve => {
    setTimeout(() => resolve(n), 15)
  })
}

const fn = universalify.fromPromise(promiseFn)

// Works with Promises:
fn('Hello World!')
.then(result => console.log(result)) // -> Hello World!
.catch(error => console.error(error))

// Works with Callbacks:
fn('Hi!', (error, result) => {
  if (error) return console.error(error)
  console.log(result)
  // -> Hi!
})

License

MIT

RELATED POST

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin