项目作者: coderaiser

项目描述 :
functional try-catch wrapper for promises
高级语言: JavaScript
项目地址: git://github.com/coderaiser/try-to-catch.git
创建时间: 2018-02-12T11:33:37Z
项目社区:https://github.com/coderaiser/try-to-catch

开源协议:MIT License

下载


Try to Catch NPM version Build Status Coverage Status

Functional try-catch wrapper for promises.

Install

  1. npm i try-to-catch

API

tryToCatch(fn, […args])

Wrap function to avoid try-catch block, resolves [error, result];

Example

Simplest example with async-await:

  1. const tryToCatch = require('try-to-catch');
  2. const reject = Promise.reject.bind(Promise);
  3. await tryToCatch(reject, 'hi');
  4. // returns
  5. // [ Error: hi]

Can be used with functions:

  1. const tryToCatch = require('try-to-catch');
  2. await tryToCatch(() => 5);
  3. // returns
  4. [null, 5];

Advanced example:

  1. const {readFile, readdir} = require('fs/promises');
  2. const tryToCatch = require('try-to-catch');
  3. read(process.argv[2])
  4. .then(console.log)
  5. .catch(console.error);
  6. async function read(path) {
  7. const [error, data] = await tryToCatch(readFile, path, 'utf8');
  8. if (!error)
  9. return data;
  10. if (error.code !== 'EISDIR')
  11. return error;
  12. return await readdir(path);
  13. }

License

MIT