diff --git a/directly.js b/directly.js index f04cbdc..b58bac9 100644 --- a/directly.js +++ b/directly.js @@ -1,70 +1,64 @@ 'use strict'; -require('es6-promise').polyfill(); - var Directly = function (concurrence, funcs) { + + if (!Promise) { + throw 'Directly requires es6 Promises'; + } + if (!(this instanceof Directly)) { return new Directly(concurrence, funcs).run(); } this.results = []; this.concurrence = concurrence; this.funcs = funcs; - this.counter = 0; + this.competitors = []; }; Directly.prototype.run = function () { + if (this.funcs.length <= this.concurrence) { return Promise.all(this.funcs.map(function (func) { return func(); })); } - this.competitors = []; - this.promise = new Promise(function (resolve, reject) { - this.resolve = resolve; - this.reject = reject; - }.bind(this)); - - var i = this.concurrence; - while (i--) { + while (this.concurrence--) { this.executeOne(); } this.startRace(); - return this.promise; + return new Promise(function (resolve, reject) { + this.resolve = resolve; + this.reject = reject; + }.bind(this)); }; Directly.prototype.executeOne = function () { var promise = this.funcs.shift()(); + var competitors = this.competitors; this.results.push(promise); - var index = this.counter++; - promise = promise.then(function () { - return index; + competitors.push(promise); + + promise.then(function () { + competitors.splice(competitors.indexOf(promise), 1); }); - promise.__index = index; - this.competitors.push(promise); }; Directly.prototype.startRace = function () { Promise.race(this.competitors) .then(function (index) { if (!this.funcs.length) { - Promise.all(this.results) - .then(function (results) { - this.resolve(results); - }.bind(this)); - } else { - this.competitors = this.competitors.filter(function (promise) { - return promise.__index !== index; - }); - this.executeOne(); - this.startRace(); + return this.resolve(Promise.all(this.results)); } + + this.executeOne(); + this.startRace(); + }.bind(this), function (err) { this.reject(err); }.bind(this)); }; - module.exports = Directly; diff --git a/package.json b/package.json index b96ac72..b969163 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "directly", - "version": "1.0.2", + "version": "1.0.3", "description": "Like Promise.all, only less so", "main": "directly.js", "scripts": { @@ -24,10 +24,11 @@ }, "homepage": "https://github.com/wheresrhys/directly", "devDependencies": { + "es6-promise": "^2.3.0", "chai": "^3.2.0", "mocha": "^2.2.5" }, "dependencies": { - "es6-promise": "^2.3.0" + } } diff --git a/test/directly.test.js b/test/directly.test.js index e4ae5d0..ed77cda 100644 --- a/test/directly.test.js +++ b/test/directly.test.js @@ -1,5 +1,7 @@ 'use strict'; +require('es6-promise').polyfill(); + var expect = require('chai').expect; var Directly = require('../directly');