3 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個(gè)贊
您需要使它們異步。
喜歡...
const one = async () => {
//some code
return
}
const two = async () => {
//some code
return
}
const three = async () => {
//some code
return
}
然后你可以...
one().then(two).then(three)

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
解決方案:
使用數(shù)組來保存狀態(tài)和持續(xù)時(shí)間:
const states = [ { name: 'session', duration: 1500 }, { name: 'break', duration: 300 } ]
交替數(shù)組的索引以在會(huì)話和中斷之間交替。
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貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以通過使函數(shù)返回 aPromise并使用async / await關(guān)鍵字等到它們完成后再開始下一個(gè)來做到這一點(diǎn)。
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));
或者只是使用良好的老式回調(diào)。但我會(huì)選擇上述之一。
添加回答
舉報(bào)