Asynchronously control the number of concurrency

Use the Promise practiced yesterday to encapsulate a function. Calling this function can control the number of concurrent tasks to avoid too many tasks being executed at the same time. The redundant tasks are placed in the waiting queue. When the execution thread is free, the tasks in the waiting queue will be taken out for execution. ;

function limitTask(taskList = [], limit = n) {
    
    

  return new Promise((resolve, reject) => {
    
    

    const len = taskList.length

    let count = 0

    // 同时启动limit个任务

    while(limit > 0) {
    
    

      start ()

      limit -=1

    }

    function start() {
    
    

      // 从数组中拿取第一个任务

      const task = taskList.shift()

      if(task) {
    
    
      
        console.log("执行成功");
        
        if(count == len -1) {
    
    

            // 最后一个任务完成

            resolve()

          }else {
    
    

            // 完成之后,启动下一个任务

            count++

            start()

          }
      }

    }

  })

 }

//测试

limitTask(['task1', 'task2', 'task3', 'task4', 'task5'],3)

Guess you like

Origin blog.csdn.net/m0_52276756/article/details/129545378