我在React中创建了一个宠物项目,遇到了一个异步问题。我有一个承诺链,它有效,但只有一次。需要在一定的时间内不间断地重复。我试图用setInterval包装一个承诺,但是,它不能作为intended.What方法在这里使用?
let promise = new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 3000);
}).then(() => {
props.changeBreathText('Exhalation')
}).then(() => {
setTimeout(() => {
props.changeBreathText('Inhale')
}, 4000);
})
发布于 2021-01-19 15:49:22
你不能重复一个承诺-这是一次性的事情,但你可以通过将它包装在一个函数中来复制链-每当你调用一个函数时,就会创建一个新的链。
const props = {
changeBreathText: console.log
}
const delay = (time) => new Promise((resolve) => {
setTimeout(resolve, time)
})
/* with promises
const promiseChain = () =>
delay(3000)
.then(() =>
props.changeBreathText('Exhalation'))
.then(() => delay(4000))
.then(() => props.changeBreathText('Inhale')
);
function repeatChain(times, chain) {
let _chain = Promise.resolve();
for (let i = 0; i < times; i++) {
_chain = _chain.then(chain)
}
return _chain
}
*/
// with async await
async function promiseChain() {
await delay(3000)
props.changeBreathText('Exhalation')
await delay(4000)
props.changeBreathText('Inhale');
}
async function repeatChain(times, chain) {
for (let i = 0; i < times; i++) {
await chain();
}
}
repeatChain(3, promiseChain)
https://stackoverflow.com/questions/65794498
复制