diff --git a/src/map.js b/src/map.js index d2bf918be..dd7244e6d 100644 --- a/src/map.js +++ b/src/map.js @@ -10,6 +10,7 @@ var getDomain = Promise._getDomain; var util = require("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; +var async = Promise._async; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); @@ -22,10 +23,14 @@ function MappingPromiseArray(promises, fn, limit, _filter) { this._limit = limit; this._inFlight = 0; this._queue = []; - this._init$(undefined, RESOLVE_ARRAY); + async.invoke(this._asyncInit, this, undefined); } util.inherits(MappingPromiseArray, PromiseArray); +MappingPromiseArray.prototype._asyncInit = function() { + this._init$(undefined, RESOLVE_ARRAY); +}; + // The following hack is required because the super constructor // might call promiseFulfilled before this.callback = fn is set // diff --git a/test/mocha/map.js b/test/mocha/map.js index 4e99ef556..2387290c3 100644 --- a/test/mocha/map.js +++ b/test/mocha/map.js @@ -111,6 +111,48 @@ describe("Promise.map-test", function () { } ); }); + + specify("should call mapper asynchronously on values array", function() { + var calls = 0; + function mapper(val) { + calls++; + } + + var input = [1, 2, 3]; + var p = Promise.map(input, mapper); + assert(calls === 0); + return p.then(function() { + assert(calls === 3); + }); + }); + + specify("should call mapper asynchronously on promises array", function() { + var calls = 0; + function mapper(val) { + calls++; + } + + var input = [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]; + var p = Promise.map(input, mapper); + assert(calls === 0); + return p.then(function() { + assert(calls === 3); + }); + }); + + specify("should call mapper asynchronously on mixed array", function() { + var calls = 0; + function mapper(val) { + calls++; + } + + var input = [1, Promise.resolve(2), 3]; + var p = Promise.map(input, mapper); + assert(calls === 0); + return p.then(function() { + assert(calls === 3); + }); + }); }); describe("Promise.map-test with concurrency", function () {