如何在 javascript 的函数内动态链接一个 promise?

how to dynamic chain a promise inside a function in javascript?

我有以下练习:

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 秒过去了”

您可以始终使用 .then() 将单个承诺用作队列:

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);
}

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()