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

cp-fetch

v0.3.2

Published

Abortable fetch with timeout support

Downloads

47

Readme

Travis (.com) Coverage Status npm npm bundle size David

SYNOPSIS :sparkles:

cpFetch is a simple wrapper around fetch with cancelable promise (c-promise2). This lib can be used for both backend and frontend development, platform specific fetch API is provided by cross-fetch package.

Why :question:

It's good to have the ability to cancel fetch requests automatically when the related promise is canceling. Using powerful of a promise with cancelation feature lets you automatically manage fetch request cycle, handling timeouts, abort the related request when you use concurrent requests.

Features / Advantages

  • browser & node.js support
  • timeouts
  • cancellation (rejecting promise chain & aborting the related network request)
  • returns CPromise instead of native
  • automatically aborting other requests, passed to the CPromise.all, if one fails.
  • automatically aborting other requests, passed to the CPromise.race, if one of them resolves or fails.

Installation :hammer:

$ npm install cp-fetch
$ yarn add cp-fetch
// cross-platform version
const cpFetch= require('cpFetch'); 

// version that uses the global fetch API, instead of cross-fetch ponyfill 
// (for modern browsers only or in case you're using third-party polyfill)
import cpFetch from "cp-fetch/lib/native";

CDN bundle

Ready for use prebuilt UMD bundles for browser with all dependencies inside.

These module bundles are only suitable to load as a script directly from the html page. If you're using some module bunlder like webpack or rollup, please import cjs module to avoid potential duplications in your project dependencies tree.

Global module export is cpFetch.

Usage examples

Live Example

Live browser example

Abortable fetch with timeout

A simple example:

const cpFetch= require('cp-fetch');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';

const chain = cpFetch(url, {timeout: 10000})
    .then(response => response.json())
    .then(data => console.log(`Done: `, data), err => console.log(`Error: `, err))

setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms 

// you able to call cancel() at any time to cancel the entire chain at any stage
// Take into account the related network request will also be aborted

The same using generators as async function:

const cpFetch= require('cp-fetch');
const CPromise= require('c-promise2');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';

const chain= CPromise.from(function*(){
    try{
        const response= yield cpFetch(url, {timeout: 5000});
        console.log(`Done: `, yield response.json())
    }catch(err){
        console.log(`Error: `, err)
    }   
});

 setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms 

Abortable concurrent requests

const cpFetch= require('cp-fetch');
const CPromise = require('c-promise2');

const chain= CPromise.race([
    cpFetch("https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s"),
    cpFetch("https://run.mocky.io/v3/30a97b24-ed0e-46e8-9f78-8f954aead2f8?mocky-delay=5s")
]).timeout(10000).then((response)=> {
    console.log(`Result :`, response.data);
}, function (err) {
    console.warn(`We got an error: ${err}`);
});

// the slower request will be aborted

// setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms 

API Reference

The package exports a wrapped version of the fetch function.

cFetch(url, {timeout, ...nativeFetchOptions}): CPromise

Options:

timeout- the timeout before the promise and related request will be rejected/aborted.

...nativeFetchOptions- other native options of the fetch function.

Learn more about CPromise features

Related projects

  • cp-axios - a simple axios wrapper that provides an advanced cancellation api
  • c-promise2 - promise with cancellation and progress capturing support
  • use-async-effect2 - cancel async code in functional React components
  • cp-koa - Koa with cancelable middlewares

License

The MIT License Copyright (c) 2020 Dmitriy Mozgovoy [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.