我正在尝试返回在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';
}
由于
答案 0 :(得分:1)
你可以使用Promise!
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! */
})
}
async
/ await
const mainLogic = async _ => {
const teaserBackground = await renderTeaserBackground()
/* Use teaserBackground as you need! */
}