Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cb-q

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cb-q

Converts callbacks to promises and creates promises from callbacks.

  • 0.0.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

cb-q

Use cb-q to handle callbacks as a deferred object when a callback exists or create a deferred object when a callback does not exist.

install

npm install cb-q

Motivation

Promises is a great pattern but many libraries use Error-First Callbacks. Since the promise pattern returns a deferred object and asyncronous functions require a callback and usually return undefined, why can't we do both.

Usage

Create an async function than handel both callbacks and promises.

var cbQ = require('cb-q');
asyncFunction(foo, cb()){
    var deferred = cbQ.defer(cb);
    //do some async stuff
    process.nextTick(function(){
        //on success
        if(success){
            deferred.resolve("yes it worked")
         } else {
          // on error
            deferred.reject();
         }
    })
    return deferred.promise;
}

Creating a callback that I can pass into a method expecting an error-first callback and expose a promise.

var cbQ = require('cb-q');
var callback = cbQ.cb();
callback.promise.then(function(result){
    //handle success
}, function(err){
    //handle error
});
fs.readFile('some-file.txt', callback);

If you already have a promise and simply want to execute a callback when the promise is resolve

var cbQ = require('cb-q');
var deferred = q.defer();
var promise = deferred.promise;
deferred.resolve('resolved');
var callback = function(err, result){
    if(err){
        throw(err);
    }
    console.log(result);
}
cbQ.resolve(promise, callback);
fs.readFile('some-file.txt', callback);

Test

npm test

Keywords

FAQs

Package last updated on 15 Oct 2014

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc