How can I limit Q promise concurrency?

前端 未结 4 1300
时光取名叫无心
时光取名叫无心 2020-12-09 19:31

How do I write a method that limits Q promise concurrency?

For instance, I have a method spawnProcess. It returns a Q promise.
I want no more than 5

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

    I wrote a little library to do this: https://github.com/suprememoocow/qlimit

    It's extremely easy to use and is specifically designed to work with Q promises:

    var qlimit = require('qlimit');
    var limit = qlimit(2); // 2 being the maximum concurrency
    
    // Using the same example as above
    return Q.all(items.map(limit(function(item, index, collection) { 
      return performOperationOnItem(item);
    }));
    

    It can also be used to limit concurrency to a specific resource, like this:

    var qlimit = require('qlimit');
    var limit = qlimit(2); // 2 being the maximum concurrency
    
    var fetchSomethingFromEasilyOverwhelmedBackendServer = limit(function(id) {
      // Emulating the backend service
      return Q.delay(1000)
        .thenResolve({ hello: 'world' }); 
    });
    

提交回复
热议问题