顺序打印,元素出现的延迟取决于元素的序列号

问题描述 投票:0回答:1

我想打印数字序列;它应始终以1开头,并在1秒(1000毫秒)的延迟后显示。列表中的下一个数字2应在2秒钟的延迟后打印,在前一个数字(即1)打印之后,依此类推,直到达到给定的限制。它已按顺序完成。

1应该在1秒的时间打印

2应该在3秒的时间打印

3应该在6秒钟的时间上打印,依此类推。

我想到了两种方法,要么使用Promises要么使用Generator函数/ async-await

我的问题是关于第一种方法,即使用Promise。

a。使用setTimeout时,我没有得到正确的顺序

b。而使用分块/延迟功能可以给我正确的结果。

a。使用setTimeout时,我没有得到正确的顺序

与这种行为相矛盾的原因:传递给浏览器/Node.js的Timer功能的每个任务,等待超时完成,完成后,将任务推入调用堆栈。

Promise.then保证在处理从onFullfillment数组开始的下一个函数/回调之前,解析上一个thenable。

有人能以正确的直觉建议我还是帮助我以正确的理解。

(function printAsyncInOrder(limit) {
  let [, ...list] = [...Array(limit + 1).keys()];

  list.reduce(chainedSequence, Promise.resolve());

  function chainedSequence(chain, currentOrder, index) {
    return chain.then(() => {
      let i = index;
      let current = currentOrder;
      //  setTimeout(() => console.log(`Hi ${index} ${new Date()}`), i * 1000)

      blocker(current * 1000);
    });
  }

  function blocker(time) {
    let timeNow = new Date();
    while (new Date() - timeNow < time) {}
    console.log(`hi ${time} ${new Date()}`);
  }
})(10);

使用setTimeout:

Hi 2 Sun Nov 10 2019 11:37:44
Hi 3 Sun Nov 10 2019 11:37:45
Hi 4 Sun Nov 10 2019 11:37:46
Hi 5 Sun Nov 10 2019 11:37:47
Hi 6 Sun Nov 10 2019 11:37:48
Hi 7 Sun Nov 10 2019 11:37:49
Hi 8 Sun Nov 10 2019 11:37:50
Hi 9 Sun Nov 10 2019 11:37:51
Hi 10 Sun Nov 10 2019 11:37:52

使用阻止程序/延迟功能

hi 2000 Sun Nov 10 2019 11:38:29
hi 3000 Sun Nov 10 2019 11:38:32
hi 4000 Sun Nov 10 2019 11:38:36
hi 5000 Sun Nov 10 2019 11:38:41
hi 6000 Sun Nov 10 2019 11:38:47
hi 7000 Sun Nov 10 2019 11:38:54
hi 8000 Sun Nov 10 2019 11:39:02
hi 9000 Sun Nov 10 2019 11:39:11
hi 10000 Sun Nov 10 2019 11:39:21
javascript asynchronous settimeout es6-promise
1个回答
0
投票

您需要在chain.then(() => {中返回一个在超时后解决的承诺

喜欢这样

(function printAsyncInOrder(limit) {
  let [, ...list] = [...Array(limit + 1).keys()];

  list.reduce(chainedSequence, Promise.resolve());

  function chainedSequence(chain, currentOrder, index) {
    return chain.then(() => {
      let current = currentOrder;
      return new Promise(resolve => setTimeout(() => {
        console.log(`Hi ${index} ${new Date()}`);
        resolve();
      }, 1000 * index));
    });
  }
})(10);
© www.soinside.com 2019 - 2024. All rights reserved.