選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
rpm-mcarman b9f7ec4306 First Commit 3年前
..
dist First Commit 3年前
src First Commit 3年前
LICENSE First Commit 3年前
README.md First Commit 3年前
package.json First Commit 3年前

README.md

npm downloads build dependencies dev dependencies tested with jest

Make-Cancellable-Promise

Make any Promise cancellable.

tl;dr

  • Install by executing npm install make-cancellable-promise or yarn add make-cancellable-promise.
  • Import by adding import makeCancellablePromise from 'make-cancellable-promise.
  • Do stuff with it!
    const { promise, cancel } = makeCancellablePromise(myPromise);
    

User guide

makeCancellablePromise(myPromise)

A function that returns an object with two properties:

promise and cancel. promise is a wrapped around your promise. cancel is a function which stops .then() and .catch() from working on promise, even if promise passed to makeCancellablePromise resolves or rejects.

Usage

const { promise, cancel } = makeCancellablePromise(myPromise);

Typically, you’d want to use makeCancellablePromise in React components. If you call setState on an unmounted component, React will throw an error.

Here’s how you can use makeCancellablePromise with React components:

class MyComponent extends Component {
  state = {
    status: 'initial',
  }

  componentDidMount() {
    this.cancellable = makeCancellable(fetchData());

    this.cancellable.promise
      .then(() => this.setState({ status: 'success' }))
      .catch(() => this.setState({ status: 'error' }));
  };

  componentWillUnmount() {
    this.cancellable.cancel();
  }

  render() {
    const { status } = this.state;

    const text = (() => {
      switch (status) {
        case 'pending': return 'Fetching…';
        case 'success': return 'Success';
        case 'error': return 'Error!';
        default: return 'Click to fetch';
      }
    })();

    return (
      <p>{text}</p>
    );
  }
}

or with React Hooks:

function MyComponent() {
  const [status, setStatus] = useState('initial');

  useEffect(() => {
    const { promise, cancel } = makeCancellable(fetchData());

    promise
      .then(() => setStatus('success'))
      .catch(() => setStatus('error'));

    return () => {
      cancel();
    };
  }, []);

  const text = (() => {
    switch (status) {
      case 'pending': return 'Fetching…';
      case 'success': return 'Success';
      case 'error': return 'Error!';
      default: return 'Click to fetch';
    }
  })();

  return (
    <p>{text}</p>
  );
}