smart-promise

3.0.2 • Public • Published

Smart Promise

Smart Promise is a Promise extension that provides filtered catch handler.

license release semantic

Benchamrks

latest results

bluebird      x  3,541 ops/sec ±1.70% (82 runs sampled)
smart-promise x 99,766 ops/sec ±1.24% (86 runs sampled)

Install

npm install smart-promise

API

The same native Promise API applies, the only difference is the catch() method.

.catch(onRejected)

Behaves normally as per the native Promise API

.catch(class ErrorClass | class CustomErrorClass | ... , onRejected)

A filtered variant of catch (like other non-JS languages typically have) that lets you only handle specific errors.

The catch handler that is first met that has eligible constructors specified, is the one that will be called.

Example

Extend your existing Promise Libraries:

const { Smart } = require('smart-promise')

const Promise = Smart(MyPromiseLib)

// or, use the shorthand
const Promise = require('smart-promise')(MyPromiseLib)

Standalone:

const { Promise } = require('smart-promise')
Promise
  .then(_ => return a.b.c.d())

  .catch(TypeError, error => {
    // If the error is a "TypeError", this code block will execute
  })

  .catch(ReferenceError, error => {
    // If the error is a "ReferenceError", this code block will execute instead
  })

  .catch('TypedErrorName', error => {
    // If the error constructor matches "TypedErrorName", this code block will execute instead
  })

  .catch(error => {
  // Generic catch-the rest (error wasn't TypeError nor ReferenceError)
  })

You may also add multiple filters for a catch handler:

Promise
  .then(_ => return a.b.c.d())

  .catch(TypeError, ReferenceError, error => {
    // Will end up here on programmer error
  })

  .catch(NetworkError, TimeoutError, 'SomeError', error => {
    // Will end up here on expected everyday network errors
  })

  .catch(error => {
    // Catch any unexpected errors
  })

You can also wrap it around existing promises resolvers, this is useful for managing 3rd party generated promises:

const { Promise } = require('smart-promise')
const Library = require('some-other-promise-producting-library')

Promise.resolve(Library.action())
  .catch('SomeError', error => {})

ESlint

If you're using ESlint or similar tooling, please refer to prefer-promise-reject-errors


Author: Ahmad Nassri • Twitter: @AhmadNassri

Readme

Keywords

Package Sidebar

Install

npm i smart-promise

Weekly Downloads

3

Version

3.0.2

License

MIT

Unpacked Size

7.6 kB

Total Files

4

Last publish

Collaborators

  • ahmadnassri