简体   繁体   中英

How to resolve a promise on button click and use it to abort a request to server in javascript?

I want to stop downloading data on cancel button click. While downloading data if user clicks the cancel button it should stop downloading the data, ie cancel the request to server.

Below is the code:

export default class ParentComponent extends React.PureComponent {
  constructor() {
    this.state = {
      load_cancel: false
    };
  }

  componentDidMount() {
    if (this.props.item) {
      this.load_item_data();
    }
  }

  load_cancel = () => {
    this.setState({ load_cancel: true });
  };

  load_item_data = () => {
    const props = this.props;
    this.file_download_status = {};
    if (this.on_item_changed) {
      this.on_item_changed();
    }
    if (this.load_cancel) {
      this.load_cancel();
    }

    const item_changed = new Promise(resolve => {
      this.on_item_changed = resolve;
    });
    const load_cancel = new Promise(resolve => {
      this.load_cancel = resolve;
    });
    const abort_loading = Promise.race([item_changed, this.unmount]);

    item
      .load(props.item.id, gl, this.update_download_progress, abort_loading)
      .then(result => {
        this.files = result.files;
        this.setState({
          item_download_done: true
        });
        client.add_item_view(props.item.id, abort_loading);
      });
  };
}

export default class ChildComponent extends React.PureComponent {
  render() {
    <button onClick={this.props.load_cancel}>Cancel</button>;
  }
}

I have tried to resolve the load_cancel in load_item_data method which works sometimes and not always meaning stops downloading data sometimes and not always.

So i understood that i have to resolve the promise on user click and use to cancel load_item_data when abort_loading is resolved.

How do i resolve promise on user clicking cancel button and use it in promise.race within load_item_data. Could someone help me with this? Thanks.

看起来这不是一个好习惯,但是您在发出请求时应在状态中保存Promise,并在load_cancel仅从状态中接受承诺并中止它。

I'm not sure if its just a syntax problem in react, could you try the javascript version of promises:

const item_changed = new Promise((resolve) => { 
         resolve(this.on_item_changed); });
const load_cancel = new Promise((resolve) => { 
            resolve(this.load_cancel);
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM