deferize
v0.1.0
Published
transforms a callback-based function into a JQDeferred promise
Downloads
4
Readme
deferize
deferize
will turn any nodish callback-based function into a jQuery Promise.
It seems I always need something like this in my projects as of late so I figured others probably do too and I decided to extract it into its own tiny module.
Install
npm install deferize --save
Usage
The most basic use of deferize
is by feeding it a function.
var fs = require( "fs" );
var open = deferize( fs.open );
What you get is a new function that is no longer callback-based but returns a promise instead.
For instance, you'd use the previous example as follows:
open( "path/to/my/file", "r" ).done( function( fd ) {
// we have the file descriptor
} ).fail( function( error ) {
// something went wrong
} );
No Error Argument
Sometimes a callback doesn't get an error as its first argument. In that case, you should call deferize.noerror
:
var fs = require( "fs" );
var exists = deferize.noerror( fs.exists );
The underlying promise will be resolved if the first argument is trueish and rejected otherwise:
exists( "path/to/my/file" ).done( function( flag ) {
// file does exist, flag === true
} ).fail( function( flag ) {
// file does not exist, flag === false
} );
Synchronous Functions
For those rare situations where you need to deferize a synchronous function, you can use deferize.sync
:
var divide = deferize.sync( function( a, b ) {
return a / b;
} );
divide( 50, 5 ).done( function( result ) {
result === 10; // true
} );
License
Copyright (c) 2012 - 2014 Julian Aubourg Licensed under the MIT license.