Batch Promises in Javascript

Do you know how to batch promises in Javascript?

I encountered this question in a interview where interviewer asked me to batch promises in "batch_size" of 10,

Question: A array [p1,p2,p3,p4.........p1000] of size "1000" filled with promises is given, we have to execute all the promises but in a batch size = 10.

Answer:

Right now, I have taken a small example of array of size = 10 and batchSize = 3

const p1 = (idx) =>{
    return new Promise((resolve,reject) =>{
         setTimeout(() =>{
             resolve(`p${idx} settled`)
         }, 1000);
    })
}

const tasks = [p1,p1,p1,p1,p1,p1,p1,p1,p1,p1];

const asyncBatchProcessing = async (tasks,batchSize) =>{
     let activeTasks = [];
     
     for(let i = 0;i<tasks.length;i++){
         if(activeTasks.length >= batchSize){
             await Promise.race(activeTasks);
         }
         const currentTask = tasks[i](i).then((data) =>{
              console.log(data);
              activeTasks.splice(activeTasks.indexOf(tasks[i]),1);
         }).catch((err) =>{
             activeTasks.splice(activeTasks.indexOf(tasks[i]),1);
         });
         
         activeTasks.push(currentTask);
     }
}

asyncBatchProcessing(tasks,3)        

Firstly, I have declared a function p1 which return a promise, then I declared this array "tasks" of size(10). Now, the main challenge was to process the next set of promises after the promises of previous batch got fired. I used "Promise.race" to get the value of first settled promise from the batch. Try to debug yourself to understand better and let me know another approaches to tackle this problem and edgecases as well :)

Follow or connect Harsh Jain for more..??

#Javascript #Promises #ProblemSolving

Raj Gautam

DevOps Engineer@CSG International || Ex @Great Learning, Material Depot (YC W22), Kroto (Backed by 100x.vc)

1 年

Informative ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了