npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

using-try-catch

v0.5.0

Published

Simplify the use of try-catch

Downloads

12

Readme

Using Try Catch

Simplify the use of try-catch. Avoid writing code that contains high scope decoupling with using-try-catch.

Main Branch Coverage Status GitHub license GitHub issues GitHub stars CDN jsdelivr Vulnerability npm npm

Installation

$ npm install using-try-catch

// OR

$ yarn add using-try-catch

// OR

$ pnpm add using-try-catch

The problem

Several times we need to scope our async/await as follows:

const axios = require('axios');

const fetchDog = async () => {
  const { data } = await axios('https://dog.ceo/api/breeds/image/random');
  return data;
}

const example = async () => {
  let promise1;
  let promise2;
  let err = false;

  try {
    promise1 = await fetchDog();
  } catch {
    err = true;
  }

  try {
    promise2 = await fetchDog();
  } catch {
    err = true;
  }

  if (err) {
    return 'Boom'
  }

  return {
    dog1: promise1,
    dog2: promise2
  }
};

example();

With using-try-catch we can simplify this operation as follows

const axios = require('axios');

const fetchDog = async () => {
  const { data } = await axios('https://dog.ceo/api/breeds/image/random');
  return data;
}

const example = async () => {
  const promise1 = await usingTryCatch(fetchDog());
  const promise2 = await usingTryCatch(fetchDog());

  if (promise1.err || promise2.err) {
    return 'Boom';
  }

  return {
    text1: promise1.data,
    text2: promise2.data
  }
};

example();

Or you can group all promises

const axios = require('axios');

const fetchDog = async () => {
  const { data } = await axios('https://dog.ceo/api/breeds/image/random');
  return data;
}

const example = async () => {
  const _promise = [
    fetchDog(),
    fetchDog(),
    fetchDog()
  ]

  const promise = await usingTryCatch(_promise);

  if promise.err {
    return 'Boom';
  }

  return {
    promise1: promise.data[0],
    promise2: promise.data[1],
    promise3: promise.data[2],
  };
}

example();

Live Demo

In order to carry out a test without cloning or installing the repository, you can test directly through CodeSandbox in an example I created.

Edit admiring-sun-5qry6

Examples

Typescript

import usingTryCatch from 'using-try-catch';

const example = async () => {
  const promise = new Promise((resolve) => resolve('exemple'));

  const result = await usingTryCatch(promise);
  console.log(result.data); // 'example'
};

example();

CommonJS

const usingTryCatch = require('using-try-catch');

const example = async () => {
  const promise = new Promise((resolve) => resolve('exemple'));

  const result = await usingTryCatch(promise);
  console.log(result.data); // 'example'
};

example();

Browser Examples

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1" name="viewport">
    <title>Example using-try-catch</title>
  </head>
  <body>
    <p id="loading">Loading...</p>
    <img id="dog-1" />
    <img id="dog-2" />

    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/usingTryCatch.js"></script>
    <script>
      document.addEventListener('DOMContentLoaded', function loaded() {

        const fetchDog = async () => {
          const res = await fetch('https://dog.ceo/api/breeds/image/random');
          const data = await res.json();

          return data;
        };

        const bootstrap = async () => {
          const result = await usingTryCatch([fetchDog(), fetchDog()]);
          
          if (result.error) {
            document.getElementById('loading').innerText = result.error;
          } else {
            document.querySelector('[id="dog-1"]').src = result.data[0].message;
            document.querySelector('[id="dog-2"]').src = result.data[1].message;
            document.querySelector('[id="loading"]').innerText = '';
          }
        };
        
        bootstrap();
      });
    </script>
  </body>
</html>

Fetch Example

const https = require('https');
const { usingTryCatch } = require('using-try-catch');

const fetchDog = () => new Promise((resolve, reject) => {
  const options = {
    host: 'dog.ceo', //Xdog.ceo
    path: '/api/breeds/image/random',
    method: 'GET',
    port: 443
  };

  const request = https.request(options, (res) => {
    res.setEncoding('utf-8');

    let body = '';
    res.on('data', (chunk) => body += chunk);
    res.on('end', () => resolve(JSON.parse(body)));
    res.on('error', (error) => reject(error));
  });

  request.on('error', (error) => reject(`Error in request: ${error}`));
  request.end();
});

const fetchData = async () => {
  const { data, error } = await usingTryCatch(fetchDog());

  if (error) {
    return console.log('Error => ', error); // Error in request: Error: getaddrinfo ENOTFOUND Xdog.ceo
  }

  return console.log('Data => ', data); // { message: 'https://images.dog.ceo/breeds/terrier-fox/n02095314_3189.jpg', status: 'success' }
};

fetchData();

Promise example

const usingTryCatch = require('using-try-catch');

const example = async () => {
  const promise = new Promise((resolve) => resolve('exemple'));

  const result = await usingTryCatch(promise);
  console.log(result.data); // 'example'
};

example();

NPM Statistics

NPM

License

Licensed under MIT

FOSSA Status