react-sigma
react-sigma copied to clipboard
Use async/await instead of callbacks
_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();
}
Is it just "copy&paste" replacement throughout the code?
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();
}