ES6 Promise replacement of async.eachLimit / async.mapLimit

前端 未结 4 1051
南方客
南方客 2020-12-03 22:54

In async, if I need to apply a asynchronousfunction to 1000 items, I can do that with:

async.mapLimit(items, 10, (item, callback) => {
    foo(item, callb         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 23:19

    This is the closest one to async.eachLimit

    Promise.eachLimit = async (coll, limit, asyncFunc) => {
    let ret = [];
        const splitArr = coll.reduce((acc,item,i)=> (i%limit) ? acc :[...acc,coll.slice(i,i+limit)],[])
        for(let i =0; i< splitArr.length;i++){
            ret[i]=await Promise.all(splitArr[i].map(ele=>asyncFunc(ele)));
        }
        return ret;
    }
    
    const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
    
    async function foo(s) {
      await wait(Math.random() * 2000);
      console.log(s);
      return s.toLowerCase();
    }
    
    (async () => {
      let arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
      console.log((await Promise.eachLimit(arr, 5, foo)));
    })();

提交回复
热议问题