Skip to content

Commit

Permalink
Merge pull request #1221 from overlookmotel/map-async
Browse files Browse the repository at this point in the history
`.map` callback called async (closes #1148)
  • Loading branch information
petkaantonov committed Sep 1, 2016
2 parents 1f5bdfd + 3a39c11 commit 1739e31
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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
//
Expand Down
42 changes: 42 additions & 0 deletions test/mocha/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down

0 comments on commit 1739e31

Please sign in to comment.