pledge.js 779 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. var RingBuffer = require('./ring_buffer');
  3. var Pledge = function() {
  4. this._complete = false;
  5. this._callbacks = new RingBuffer(Pledge.QUEUE_SIZE);
  6. };
  7. Pledge.QUEUE_SIZE = 4;
  8. Pledge.all = function(list) {
  9. var pledge = new Pledge(),
  10. pending = list.length,
  11. n = pending;
  12. if (pending === 0) pledge.done();
  13. while (n--) list[n].then(function() {
  14. pending -= 1;
  15. if (pending === 0) pledge.done();
  16. });
  17. return pledge;
  18. };
  19. Pledge.prototype.then = function(callback) {
  20. if (this._complete) callback();
  21. else this._callbacks.push(callback);
  22. };
  23. Pledge.prototype.done = function() {
  24. this._complete = true;
  25. var callbacks = this._callbacks, callback;
  26. while (callback = callbacks.shift()) callback();
  27. };
  28. module.exports = Pledge;