react-sigma icon indicating copy to clipboard operation
react-sigma copied to clipboard

Use async/await instead of callbacks

Open dunnock opened this issue 8 years ago • 2 comments

	_load(url: string) {
		sigma.parsers.gexf(
			this.props.path ,
			this.props.sigma ,
			this.onLoad
		)
	}

	_onLoad() {
		if(this.props.sigma)
		this.props.sigma.refresh()
		this.setState({loaded:true})
		if(this.props.onGraphLoaded)
			return this.props.onGraphLoaded()
	}

can be written as:

  loadGexf() {
    return new Promise((resolve) => sigma.parsers.gexf(this.props.path, this.props.sigma, resolve));
  }

  async load() {
    const sigma = this.props.sigma;
    if(!sigma) return;
    await loadGexf();
    sigmaI.refresh();
    this.setState({loaded:true});
    this.props.onGraphLoaded &&
      this.props.onGraphLoaded();
  }

dunnock avatar May 07 '17 13:05 dunnock

Is it just "copy&paste" replacement throughout the code?

avoloschuk avatar Jun 20 '17 20:06 avoloschuk

No, basically you replace callbacks

sigma.parsers.gexf(
			this.props.path ,
			this.props.sigma ,
			this.onLoad
		)

with async/await:

  await loadGexf();

but it requires:

  • function taking callback converted to Promise:
loadGexf() {
    return new Promise((resolve) => sigma.parsers.gexf(this.props.path, this.props.sigma, resolve));
  }
  • async function body (in this specific piece of code it is as below, in other placed whenever function instantiating callback is called):
  async load() {
    const sigma = this.props.sigma;
    if(!sigma) return;
    await loadGexf();
    sigmaI.refresh();
    this.setState({loaded:true});
    this.props.onGraphLoaded &&
      this.props.onGraphLoaded();
  }

dunnock avatar Jun 21 '17 06:06 dunnock