我正在尝试返回在 setTimout 中计算的值。但似乎我无法获得这个值。我读到要做到这一点我必须使用 promise 。我是否有义务像这样使用这个例子: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';
}
谢谢
最佳答案
您可以使用 Promise!
ES6 方式 - 标准 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! */
})
}
ES7 方式 - Harmony async
/await
const mainLogic = async _ => {
const teaserBackground = await renderTeaserBackground()
/* Use teaserBackground as you need! */
}
关于javascript - 从 setTimeout 返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48894703/