theydy / notebook

记录读书笔记 + 知识整理,vuepress 迁移中 https://theydy.github.io/notebook/
0 stars 0 forks source link

异步求和 #22

Open theydy opened 3 years ago

theydy commented 3 years ago

const addRemote = async (a, b) => new Promise(resolve => {
  setTimeout(() => resolve(a + b), 1000)
})

async function add(...args) {
  if (args.length <= 1) return Promise.resolve(...args);

  if (args.length === 2) {
    return addRemote(args[0], args[1]);
  }

  const promiseList = [];

  for (let i = 0; i < args.length ; i+=2) {
    promiseList.push(addRemote(args[i], args[i + 1] || 0))
  }

  const res = await Promise.all(promiseList);
  return add(...res);
}

// test
add(1, 2).then(res => {
  console.log(res);
})

add(1, 2, 3, 4, 5, 6, 7).then(res => {
  console.log(res);
})