wangjs-jacky / js-challenges

0 stars 0 forks source link

js每隔一秒打印1,2,3,4,5 #4

Open wangjs-jacky opened 1 year ago

wangjs-jacky commented 1 year ago

方案一:基于 tapable 思想,构建 Promise 执行串

const sleep = (delay = 1000) => {
  return new Promise(resolve => {
    setTimeout(resolve, delay);
  });
}

/* promise 串实现 */
[1, 2, 3, 4, 5].reduce((pre, cur) => {
  return pre.then(() => {
    console.log(cur);
    return sleep();
  })

}, Promise.resolve())
wangjs-jacky commented 1 year ago

方案二:基于 koacompose 实现。

/* 
  题目:js每隔一秒打印1,2,3,4,5
*/

const sleep = (delay = 1000) => {
  return new Promise(resolve => {
    setTimeout(resolve, delay);
  });
}

/* compose 串实现 */
const tasks = [1, 2, 3, 4, 5].map((i) => {
  return (next) => {
    setTimeout(() => {
      console.log(i);
      next();
    }, 1000);
  }
})

function compose(tasks) {
  const dispatch = (i) => {
    if (i === tasks.length) return;
    const curTask = tasks[i];
    const next = () => dispatch(i + 1);
    return curTask(next);
  };

  dispatch(0);
}

compose(tasks)