【问题标题】:how to dynamic chain a promise inside a function in javascript?如何在javascript中的函数内动态链接promise?
【发布时间】:2021-05-31 09:19:12
【问题描述】:

我有以下练习:

let standInLine = (() => {
  return function(logAfter) {
    return function b(seconds) {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log(`${seconds} has passed`)
          resolve(b(seconds));
        }, seconds * 1000);
      }) //what to do here to chain the promises
    }
  }
})();
{
  let politeLogAfter = standInLine(logAfter);
  politeLogAfter(5);
  politeLogAfter(3);
  politeLogAfter(4);
}

我需要链接承诺,换句话说,我需要动态链接返回的承诺,我应该在函数 standInLine 中添加 .then() 但我不知道该怎么做,有什么帮助吗? 结果应该是:

暂停 5 秒

记录“5秒过去了”

暂停 3 秒

记录“3 秒过去了”

暂停 4 秒

记录“4秒过去了”

【问题讨论】:

  • 你能详细说明一下结果应该是什么吗?
  • 我编辑问题
  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?

标签: javascript promise chaining


【解决方案1】:

您可以通过始终在其上使用 .then() 来将单个 Promise 用作队列:

let standInLine = (() => {
  // create a queue
  let queue = Promise.resolve();

  return function(logAfter) {
    return function b(seconds) {
      //add to the end of the queue
      queue = queue.then(() => new Promise((resolve) => {
        setTimeout(() => {
          console.log(`${seconds} has passed`)
          resolve(b(seconds));
        }, seconds * 1000);
      }))
    }
  }
})();
const logAfter = 10;
{
  let politeLogAfter = standInLine(logAfter);
  politeLogAfter(5);
  politeLogAfter(3);
  politeLogAfter(4);
}

【讨论】:

    【解决方案2】:

    const sleep = (seconds) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve()
        }, seconds * 1000)
      })
    }
    
    const standInLine = async(seconds) => {
      await sleep(seconds)
      console.log(`${seconds} has passed`)
    }
    
    const chain = async() => {
      await standInLine(5)
      await standInLine(3)
      await standInLine(2)
    }
    
    chain()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      • 2015-10-06
      • 2020-12-06
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多