wangjs-jacky / js-challenges

0 stars 0 forks source link

实现 Promise 串行,不考虑 waterfall | Bail 场景 | 传参 ...args 等场景 #6

Open wangjs-jacky opened 1 year ago

wangjs-jacky commented 1 year ago

题目:Promise 串行 不考虑 waterfall | Bail | 传参 ...args 等场景

测试代码:

const sleep = (delay = 1000) => {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log("Hello world");
      resolve();
    }, delay);
  });
}

const tasks = [sleep, sleep, sleep];

预期结果:打印三次 Hello world

wangjs-jacky commented 1 year ago

方案一:构建 promise

const tasks = [sleep, sleep, sleep];

/* 构建 promise 的 .then 串 */
function asyncFn(tasks) {
  const [first, ...otherTasks] = tasks;
  otherTasks.reduce((pre, cur) => {
    return pre.then(() => cur())
  }, first());
}

asyncFn(tasks);
wangjs-jacky commented 1 year ago

方案二: async + await

const tasks = [sleep, sleep, sleep];

/* 基于 async + await 实现 */
async function asyncFn() {
  for (let i = 0; i < tasks.length; i++) {
    try {
      await tasks[i]();
    } catch (error) { }
  }
}

asyncFn(tasks);