尼采般地抒情

公告栏

此网站主题为本人手写主题, 主题待开源···

站点信息

文章总数目: 305
已运行时间: 1063
目录
  1. 参考:

尼采般地抒情

尼采般地抒情

公告栏

此网站主题为本人手写主题, 主题待开源···

站点信息

文章总数目: 305
已运行时间: 1063

前言:使用Typescript编写如下函数功能 并发控制函数 要求控制任务执行的并发上限为concurrency

/*

- @Author: wztlink1013
- @Date: 2022-07-25 19:57:09
- @LastEditTime: 2022-07-25 19:57:22
- @Description:
  \*/
  // Practice 1
  const test_1 = () => {
  return new Promise(resolve => {
  setTimeout(() => {
  console.log('2000')
  let myDate = new Date()
  console.log('---- ', myDate.toTimeString().substring(0, 8), ' ----')
  resolve(2000)
  }, 2000)
  })
  }
  const test_2 = () => {
  return new Promise(resolve => {
  setTimeout(() => {
  console.log('3000')
  let myDate = new Date()
  console.log('---- ', myDate.toTimeString().substring(0, 8), ' ----')
  resolve(3000)
  }, 3000)
  })
  }
  const test_3 = () => {
  return new Promise(resolve => {
  setTimeout(() => {
  console.log('4000')
  let myDate = new Date()
  console.log('---- ', myDate.toTimeString().substring(0, 8), ' ----')
  resolve(4000)
  }, 4000)
  })
  }

let arr = [test_1, test_2, test_3]

async function parallel(
tasks: (() => void)[],
concurrency: number
): Promise<void> {
const ret: any[] = []
const executing: any[] = []

let myDate = new Date()
console.log('----start ', myDate.toTimeString().substring(0, 8), ' ----')

for (const item of tasks) {
const p = Promise.resolve().then(item)
ret.push(p)

    if (concurrency <= tasks.length) {
      const e: any = p.then(() => executing.splice(executing.indexOf(e), 1))
      executing.push(e)
      if (executing.length >= concurrency) {
        await Promise.race(executing)
      }
    }

}
// return Promise.all(ret);
}
parallel(arr, 2)

参考:

评论区

Twikoo giscus