a-wait-forit
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

Async/await without try/catch.

About

Allows to use async/await with no try/catch to handle errors.

Usage

Use await with function that might throw an error without try/catch

const { forit } = require('a-wait-forit')

async function(){
  const [ err, data ] = await forit(fetchSomething())
  // assert.equal(err, undefined)
  // assert.ok(data)

  const [ err ] = await forit(fetchThatThrowsError())
  // assert.ok(err)
}

Use async/await plus middlware with custom error handilng

wait bypasses any error occurred to a next middleware by default. To prevent that behaviour you might use custom onerror function. This helps to hide sensitive messages.

const { wait } = require('a-wait-forit')

app.use('*', wait(async (req, res) => {
  const result = await doSomething()

}, (err, next) => { next(new Error('Oops. Something went wrong.')) }))

Use wait + forit

const { wait, forit } = require('a-wait-forit')

app.use('*', wait(async (req, res, next) => {
  const [err, result] = await forit(fetchThatThrowsError())

  if(err) {
    res.status(500);
    res.send(new Error('Oops. Something went wrong.')) 
  }
}))

forit adn Promise's chains

forit returns the Promise but catches any error happend internally. If you want it play well in conjunction with .then, custom onerror handler should be specified.

const { forit } = require('a-wait-forit')

forit(fetchThatThrowsError())
  .then((_) => {
    // assert.ok(_[0] instanceof Error)
  })

forit(fetchThatThrowsError(), _ => { throw _ })
  .catch((_) => {
    // assert.ok(_ instanceof Error)
  })

/a-wait-forit/

    Package Sidebar

    Install

    npm i a-wait-forit

    Weekly Downloads

    101

    Version

    0.2.0

    License

    MIT

    Unpacked Size

    8.39 kB

    Total Files

    11

    Last publish

    Collaborators

    • rogaldh