How to limit (or queue) calls to external processes in Node.JS?

后端 未结 3 1109
一个人的身影
一个人的身影 2021-01-05 05:34

Scenario

I have a Node.JS service (written using ExpressJS) that accepts image uploads via DnD (example). After an image is uploaded, I do a few thi

3条回答
  •  春和景丽
    2021-01-05 05:52

    For anyone who thought Brandon's quick-and-dirty might be too quick-and-dirty, here's a variation that is no longer and doesn't have the unnecessary busy-wait. I'm not in a position to test it but it should work.

    var enqueue = function() {
      var queue = [];
      var execImmediate = function(fImmediate) {
        enqueue = function(fDelayed) 
          queue.push(fDelayed);
        };
        fImmediate();
    
        var ic = setInterval(function() {
          var fQueued = queue.shift();
          if (fQueued) {
            fQueued();
          } else {
            clearInterval(ic);
            enqueue = execImmediate;
          }
        }, 1000);
      };
      return execImmediate;
    }();
    

提交回复
热议问题