catching

1.0.3 • Public • Published

catching

Catch promise reject, return as promise resolve.

Often used in async function, together with await.

Install

npm install catching

Use

import catching from 'catching'
 
async doOperation() {
  const ret = await catching(yourPromiseFn())
  // Here you need differ resolve and reject by: code or instanceof Error, etc.
  const isOK = ...
 
  if (!isOK) {
    throw ret
  }
  else {
    // ... next step
  }
}

Why

Normally when we use async/await, we would use try-catch for promise reject scenario.

But the code written by try-catch is not concise, while it indeed differentiates abnormal case from normal.

Code looks like below, addUserDAO reject promise while meeting error.

async addUserService() {
  try {
    const ret = await addUserDAO()
  }
  catch (err) {
    throw err
  }
}
 
function addUserDAO () {
  return new Promise((res, rej) => {
    // const isOK = ...
    if (OK) {
      res({ data }) 
    }
    else {
      rej({ data, code })  
    }
  })
}
 

How

import catching from 'catching'
 
async addUserService() {
  const ret = await catching(addUserDAO())
  if (!ret.code) {
    throw ret
  }
  else {
    // ... next step
  }
}
 

Links

Readme

Keywords

Package Sidebar

Install

npm i catching

Weekly Downloads

8

Version

1.0.3

License

MIT

Unpacked Size

2.3 kB

Total Files

4

Last publish

Collaborators

  • diydyq