3 回答
TA贡献1829条经验 获得超13个赞
您需要使它们异步。
喜欢...
const one = async () => {
//some code
return
}
const two = async () => {
//some code
return
}
const three = async () => {
//some code
return
}
然后你可以...
one().then(two).then(three)
TA贡献1805条经验 获得超9个赞
解决方案:
使用数组来保存状态和持续时间:
const states = [ { name: 'session', duration: 1500 }, { name: 'break', duration: 300 } ]
交替数组的索引以在会话和中断之间交替。
countDown(id){
// set the function to a variable and set state to it, so the function
// can be paused with clearInterval()
var intervalFunc = setInterval(() => down(this.state.timeLeftSeconds--), 1000);
this.setState({intervalFunc: intervalFunc});
const down = (time) =>
{
if(time > 0){
// converts seconds to MM:SS at every t-minus
this.setState({ timeLeft: secondsToMins(time)});
console.log(time);
console.log(this.state.timeLeft);
}
if (time <= 0) {
this.setState({ timeLeft: secondsToMins(time)});
let sound = document.getElementById(id).childNodes[0];
sound.play();
let stateIndex = (this.state.stateIndex + 1) % states.length;
this.setState({ stateIndex: stateIndex});
this.setState({ timeLeftSeconds: states[stateIndex].duration});
this.setState({ init: states[stateIndex].name});
console.log(this.state.init);
}
}
}
TA贡献2080条经验 获得超4个赞
您可以通过使函数返回 aPromise并使用async / await关键字等到它们完成后再开始下一个来做到这一点。
const setDelay = delay => new Promise(resolve => {
console.log(`Process running for ${delay}`);
setTimeout(() => {
console.log('Process done');
resolve();
}, delay);
});
(async () => {
await setDelay(2000);
await setDelay(3000);
await setDelay(1000);
})();
或者你可以不用async / await并链接承诺。
const setDelay = delay => new Promise(resolve => {
console.log(`Process running for ${delay}`);
setTimeout(() => {
console.log('Process done');
resolve();
}, delay);
});
setDelay(3000)
.then(() => setDelay(1000))
.then(() => setDelay(4000));
或者只是使用良好的老式回调。但我会选择上述之一。
添加回答
举报