从setTimeout返回一个值

时间:2018-02-20 21:43:10

标签: javascript reactjs promise settimeout

我正在尝试返回在setTimout中计算的值。但似乎我无法获得这个价值。我读到要做到这一点我必须使用承诺。我是否有义务使用这个例子:https://italonascimento.github.io/applying-a-timeout-to-your-promises/

我的代码:

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';
}

由于

1 个答案:

答案 0 :(得分:1)

你可以使用Promise!

ES6方式 - 标准承诺

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);
})

要在外面使用,你可以这样做:

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

ES7方式 - 和谐async / await

const mainLogic = async _ => {
    const teaserBackground = await renderTeaserBackground()
    /* Use teaserBackground as you need! */
}