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

make-cancelable-task

v0.1.13

Published

This lib will make function, promise cancelable and make axios request cancelable

Downloads

5

Readme

make-cancelable-task

make promise cancelable (include axios promise), make function cancelable

How to use

First of all you need to import this library in global index.ts (or app.ts,...)file

import "make-cancelable-task";

How to make axios promise cancelable

  • You can create your get request method like bellow , file api.ts
import Axios, { AxiosRequestConfig, CancelToken } from "axios";

const get = (
    url: string,
    config?: AxiosRequestConfig,
    cancelToken?: CancelToken
  ) =>
  api.request({
    method: "GET",
    url,
    ...config,
    cancelToken: config?.cancelToken || cancelToken,
  });
const withErrorHandler = function (cancelableApi: Function) {
  return cancelableApi()
    .makeCancelablePromise()
    .convertData(({ data, error }) => {
      if (error) {
        if (error?.message?.canceled || error?.canceled) {
          console.log("promise was canceled", error);
        }
        error.newProp = "I'm new prop";
        return error;
      } else {
        return {
          ...data,
          isOk: () => {
            console.log("you can extend more properties for response data or convert data before return response");
          },
        };
      }
    });
};

export const cancelableApi = {
  get: (...params: any) =>
    withCancelToken(get, ...((params.length = 2) && params))
  getWithErrorHandler: (...params: any) =>
    withErrorHandler(withCancelToken(get, ...((params.length = 2) && params)))
	/* (params.length = 2) && params : this code make sure params length always is 2,
  match with required params of axios.get method */
};

/*===== Now you can use  this method in request service file =====*/
import { cancelableApi } from "./api";

function getRequest = async () {
	const execute = cancelableApi.get("you request url");
	setTimeout(()=>{
		execute.cancel()
		// cancel axios request if it take longer than 1 second
	}, 1000);
	const response = await execute();
}

Make Function cancelable

  • Simple cancel timeout in executed function
import { InjectAbort } from "make-cancelable-task";

const notifyValue = ((injectEbort: InjectAbort, inputValue) => {
  const t = setTimeout(() => {
    alert("Alert value after 3 seconds", inputValue);
  }, 3000);
  injectEbort.withAbort(() => {
    clearTimeout(t);
    alert("Cancel timeout after 2 seconds");
  });
}).makeCancelable();

notifyValue("hello");

setTimeout(() => {
  notifyValue.cancel();
}, 2000);
  • Cancel request in executed function
import { InjectAbort } from "make-cancelable-task";
import { cancelableApi } from "./api";

const getDataFromServer = (async (injectEbort: InjectAbort, url: string) => {
  try {
    const response = await injectEbort(cancelableApi.get(url));
    console.log("response", response);
  } catch (error) {
    console.log("is request to url canceled? ", injectEbort.isAborted());
  }
}).makeCancelable({ delay: 200 }); // you can delay execute function in 200ms(default is 0),
// this is very usefull when many too many similar requests/functions executed close together
getDataFromServer("get-url");

setTimeout(() => {
  // cancel get data function after running 1 second
  getDataFromServer.cancel();
}, 1000);

Make promise cancelable.

  • Bellow code describer how to create a waiting call function and make it cancelable
const waiting = function (time: number = 1000, clb?: Function) {
  let timeoutValue: any;
  const promise = new Promise((resolve, reject) => {
    timeoutValue = setTimeout(() => {
      resolve(clb ? clb() : "");
    }, time);
  });
  const cancelAllSyncTask = () => {
    console.log("cancel promise in waiting function");
    clearTimeout(timeoutValue);
  };
  return promise.makeCancelablePromise(cancelAllSyncTask);
};

waiting(3000, () => {
  alert("This is called after 3 seconds");
});
setTimeout(() => {
  waiting.cancel();
}, 1000);