2

I'm trying to return a value calculated in a setTimout. But it seems like I can't do get this value. I read that to do this I must use promises. Am I obliged to use this like this exemple : https://italonascimento.github.io/applying-a-timeout-to-your-promises/ ?

My code :

renderTeaserBackground = () => {
    return setTimeout(function() {
        this.setState({ teaserAnimCount: this.state.teaserAnimCount + 1 });
        let teaserBackground = teaserBgImg[this.state.teaserAnimCount];
        console.log(teaserBackground);
    }.bind(this), this.state.teaserAnimDuration * 1000);
    return 'teaserBackground';
}

Thanks

Guillaume
  • 1,500
  • 3
  • 24
  • 33

1 Answers1

2

You can use a Promise!

ES6 way - Standard Promises:

renderTeaserBackground = () => new Promise(res => {
    setTimeout(_ => {
        this.setState({teaserAnimCount: this.state.teaserAnimCount + 1});
        let teaserBackground = teaserBgImg[this.state.teaserAnimCount]
        res(teaserBackground) //Return it here!
    }, this.state.teaserAnimDuration * 1000);
})

To use this outside, you can do:

const mainLogic = _ => {
    return renderTeaserBackground().then(teaserBackground => {
        /* Use teaserBackground as you need! */
    })
}

ES7 way - Harmony async/await

const mainLogic = async _ => {
    const teaserBackground = await renderTeaserBackground()
    /* Use teaserBackground as you need! */
}
AP.
  • 8,082
  • 2
  • 24
  • 33