首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何重复承诺链

如何重复承诺链
EN

Stack Overflow用户
提问于 2021-01-19 23:27:44
回答 1查看 99关注 0票数 0

我在React中创建了一个宠物项目,遇到了一个异步问题。我有一个承诺链,它有效,但只有一次。需要在一定的时间内不间断地重复。我试图用setInterval包装一个承诺,但是,它不能作为intended.What方法在这里使用?

代码语言:javascript
代码运行次数:0
运行
复制
let promise = new Promise((resolve) => {
        setTimeout(() => {
            resolve()
        }, 3000);
    }).then(() => {
        props.changeBreathText('Exhalation')
    }).then(() => {
        setTimeout(() => {
            props.changeBreathText('Inhale')
        }, 4000);

    })
EN

回答 1

Stack Overflow用户

发布于 2021-01-19 23:49:22

你不能重复一个承诺-这是一次性的事情,但你可以通过将它包装在一个函数中来复制链-每当你调用一个函数时,就会创建一个新的链。

代码语言:javascript
代码运行次数:0
运行
复制
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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65794498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档