React:如何强制一个函数在另一个函数完全完成后运行?

在这个 React Pomodoro Clock 中,有一个函数countDown。其中有一个函数叫做three. 当前,this.setState({ init: 'break' }); 在 中设置时twothree立即发生。但是,three应该等到two完成。任何帮助将不胜感激。



catspeake
浏览 265回答 3
3回答

烙印99

您需要使它们异步。喜欢...const one = async () => {  //some codereturn}const two = async () => {  //some codereturn}const three = async () => {  //some codereturn}然后你可以...one().then(two).then(three)

Cats萌萌

解决方案:使用数组来保存状态和持续时间:const states = [ { name: 'session', duration: 1500 }, { name: 'break', duration: 300 } ]交替数组的索引以在会话和中断之间交替。countDown(id){&nbsp; &nbsp; // set the function to a variable and set state to it, so the function&nbsp; &nbsp; // can be paused with clearInterval()&nbsp; &nbsp; var intervalFunc = setInterval(() => down(this.state.timeLeftSeconds--), 1000);&nbsp; &nbsp; this.setState({intervalFunc: intervalFunc});&nbsp; &nbsp; const down = (time) =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; if(time > 0){&nbsp; &nbsp; &nbsp; &nbsp; // converts seconds to MM:SS at every t-minus&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ timeLeft: secondsToMins(time)});&nbsp; &nbsp; &nbsp; &nbsp; console.log(time);&nbsp; &nbsp; &nbsp; &nbsp; console.log(this.state.timeLeft);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if (time <= 0) {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ timeLeft: secondsToMins(time)});&nbsp; &nbsp; &nbsp; &nbsp; let sound = document.getElementById(id).childNodes[0];&nbsp; &nbsp; &nbsp; &nbsp; sound.play();&nbsp; &nbsp; &nbsp; &nbsp; let stateIndex = (this.state.stateIndex + 1) % states.length;&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ stateIndex: stateIndex});&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ timeLeftSeconds: states[stateIndex].duration});&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ init: states[stateIndex].name});&nbsp; &nbsp; &nbsp; &nbsp; console.log(this.state.init);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }

犯罪嫌疑人X

您可以通过使函数返回 aPromise并使用async / await关键字等到它们完成后再开始下一个来做到这一点。const setDelay = delay => new Promise(resolve => {&nbsp; console.log(`Process running for ${delay}`);&nbsp; setTimeout(() => {&nbsp; &nbsp; console.log('Process done');&nbsp; &nbsp; resolve();&nbsp; }, delay);});(async () => {&nbsp;&nbsp;&nbsp; await setDelay(2000);&nbsp; await setDelay(3000);&nbsp; await setDelay(1000);&nbsp;&nbsp;})();或者你可以不用async / await并链接承诺。const setDelay = delay => new Promise(resolve => {&nbsp; console.log(`Process running for ${delay}`);&nbsp; setTimeout(() => {&nbsp; &nbsp; console.log('Process done');&nbsp; &nbsp; resolve();&nbsp; }, delay);});setDelay(3000)&nbsp; .then(() => setDelay(1000))&nbsp; .then(() => setDelay(4000));或者只是使用良好的老式回调。但我会选择上述之一。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript