From 3a39c11ab77299a163e9504e77f498118d0c3263 Mon Sep 17 00:00:00 2001 From: overlookmotel Date: Wed, 31 Aug 2016 19:30:18 +0100 Subject: [PATCH] `.map` callback called async (closes #1148) --- src/map.js | 7 ++++++- test/mocha/map.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) 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 () {