defd

1.0.0 • Public • Published

view on npm downloads per month node version build status test coverage license

Deferred

Tiny extension for native Promises to make them more suitable for Node core APIs.
The package exposes a subclass of the built-in Promise, which extends that with the following four methods.

new Deferred([executor])

Unlike Promise, Deferred does not require an executor function for instantiation, because it makes possible to resolve or reject the instance from outside the executor's scope.

const d1 = new Deferred,
      d2 = new Deferred(executor)
 
d1.resolve('sun is shining')
      
function executor(resolve, reject) {
    reject('baby is crying') // same as d2.reject(...)
}
 
d1.then(result => console.log('success:', result))
d2.catch(error => console.error('error:', error))

Output:

success: sun is shining
error: baby is crying

deferred.resolve(value)

Resolve the deferred instance.

deferred.reject(reason)

Reject the deferred instance.

deferred.done(callback)

Attach an error-first callback to the instance. It will be fired once the instance resolves or rejects.

const d1 = new Deferred,
      d2 = new Deferred
      
function handler(err, result) {
    if (err)
        console.error('error:', err)
    else
        console.log('success:', result)
}
 
d1.done(handler)
d2.done(handler)
 
d1.resolve('your pizza order has arrived')
d2.reject('something exploded')

Output:

success: your pizza order has arrived
error: something exploded

deferred.callback()

Generate an error-first callback which will resolve or reject the instance based on the first parameter passed to it.

const d1 = new Deferred,
      d2 = new Deferred,
      cb1 = d1.callback(),
      cb2 = d2.callback()
      
d1.then(result => console.log('success:', result))
d2.catch(error => console.error('error:', error))
 
cb1(null, 'your cat is purring')
cb2('coffee machine is out of order')

Output:

success: your cat is purring
error: coffee machine is out of order

Installation

With npm:

npm install defd

Tests

Run unit tests:

npm test

Run unit tests and create coverage report:

npm run cover

License

MIT

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.0
    1
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.0
    1

Package Sidebar

Install

npm i defd

Weekly Downloads

1

Version

1.0.0

License

MIT

Last publish

Collaborators

  • schwarzkopfb