npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

callback-promise

v0.5.0

Published

Convert callback style APIs to Promise based APIs

Downloads

28

Readme

callback-promise Build Status codecov

Convert callback style APIs to Promise based APIs.

Suitable for Browsers and Node.js.

Pure JS for best performance, no evals, withs or other "dangerous" constructs used.

Breaking Changes

v0.5.0

  • The this of the arguments transformation function became the promise:
const papi = c2p(obj, meth, function (...args) {
    const context = this; 
    // in v0.4 context === obj, 
    // in v0.5 context.this === obj, 
    //     and context is the promise object returned by papi()
    ...
});

let promise = papi(x, y, z);
// promise.this === obj

Install

  • Just add a script tag to your page (Browser):
<script src="https://unpkg.com/callback-promise"></script>
  • Alternatively copy c2p.js to your project or install it using npm:
npm install callback-promise
  • Then import c2p to your app (ESM):
import c2p from 'callback-promise';
  • or require c2p (AMD or CommonJs):
const c2p = require('callback-promise');
  • Make sure there is a Promise implementation or get a polyfill like es6-promise.
c2p.Promise = require('es6-promise').Promise; // polyfill

Usage

  • Convert any API based on callbacks to promises
// convert speciffic methods
var pAPI = {
    meth: c2p([API, ]API.meth, resultArgNo, errorArgNo, cbAtStart, noCb),
};

// or convert the entire API object
var pAPI = c2p.all(API[, dest_pAPI], resultArgNo, errorArgNo, cbAtStart, noCb);


// @param any      API        - a context object for API.meth.
// @param Function meth       - a function (name on API) that accepts a callback argument and optinally other arguments.
// @param int     resultArgNo - argument number of result in callback. If false, all arguments are considered the result.
// @param int     errorArgNo  - argument number of error in callback.
// @param Boolean cbAtStart   - if _fn expects callback as first argument, set this to true.
// @param Boolean noCb        - if true, the new version of _fn doesn't accept the callback argument.

// Note: All argumetns except .meth are optional

// @return Function that accepts same arguments as _fn, except callback, and returns a Promise
  • Now you can use your new pAPI
pAPI.meth(arg1, arg2, ...)
    .then(function(result){...})
    .catch(function(error){...})
;

// equivalent with old API

API.meth(arg1, arg2, ..., function (some, args, with, result, and, error){
    if ( error ) ...;
    ...
})

Examples

Node API

// Common Node.js code
fs.readFile(filename, function (error, data) {
    if ( error ) {
        ...
    }
    else {
        ...
    }
});

// convert to Promise based API:
pfs.readFile = c2p(fs.readFile, 1, 0);
// same with explicit arguments mapping
pfs.readFile = c2p(fs.readFile, function (error, data) {
    if ( error ) throw error;
    return data;
});
// or with this
pfs.readFile = c2p(fs, 'readFile', 1, 0);

// then
pfs.readFile(filename)
    .then(function (data) { })
    .catch(function (error) { })
;

Callback with sync return

// Node.js method that accepts a callback and returns an EventEmitter
var child = child_process.exec(command, options, function (error, stdout, stderr){ ... });
var pid = child.pid;
child.stdin.end();

// convert to Promise base API:
pchild_process.exec = c2p(child_process.exec, 1, 0);


// then
var pchild = pchild_process.exec(command, options);

var child = pchild.result; // like an event in jQuery
var pid = child.pid;
child.stdin.end();

pchild
    .then(function (stdout){ ... })
    .catch(function (error){ ... })
;


// and if you need to catch stderr, use the callback:
var pchild = pchild_process.exec(command, options, function (error, stdout, stderr){ ... })
    .then(function(stdout){ ... })
    .catch(function (error){ ... })
;

Chrome Extension API

// Common Chrome Extension code
chrome.tabs.update(tabId, props, function (tab) {});

// becomes:
pchrome.tabs.update = c2p(chrome.tabs.update);
// or with this
pchrome.tabs.update = c2p(chrome.tabs, 'update');
// either
pchrome.tabs.update = c2p(chrome.tabs, chrome.tabs.update);
// either with explicit arguments mapping and API error handling
pchrome.tabs.update = c2p(chrome.tabs.update, function (tab) {
    var error = chrome.runtime.lastError;
    if ( error ) throw error;
    return tab;
});

// then
pchrome.tabs.update(tabId, props)
    .then(function (tab) {})
    .catch(function (error) {})
;

Other use cases

var wait = c2p(setTimeout, true);
wait(100).then(function () { doSomethingLater() })

Testing

npm test     # test in node
npm test-dev # test in browsers using karma with livereload

to be continued ...