Skip to content

Commit

Permalink
Merge pull request #194 from dentrado/promise-support
Browse files Browse the repository at this point in the history
Handle promises
  • Loading branch information
Richard Feldman authored Mar 8, 2017
2 parents 2f8c108 + 041ef0c commit c5af0b6
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
7 changes: 7 additions & 0 deletions seamless-immutable.development.js
Original file line number Diff line number Diff line change
Expand Up @@ -612,9 +612,16 @@ function immutableInit(config) {
obj instanceof File;
}

function isPromise(obj) {
return typeof obj === 'object' &&
typeof obj.then === 'function';
}

function Immutable(obj, options, stackRemaining) {
if (isImmutable(obj) || isReactElement(obj) || isFileObject(obj)) {
return obj;
} else if (isPromise(obj)) {
return obj.then(Immutable);
} else if (Array.isArray(obj)) {
return makeImmutableArray(obj.slice());
} else if (obj instanceof Date) {
Expand Down
7 changes: 7 additions & 0 deletions src/seamless-immutable.js
Original file line number Diff line number Diff line change
Expand Up @@ -612,9 +612,16 @@ function immutableInit(config) {
obj instanceof File;
}

function isPromise(obj) {
return typeof obj === 'object' &&
typeof obj.then === 'function';
}

function Immutable(obj, options, stackRemaining) {
if (isImmutable(obj) || isReactElement(obj) || isFileObject(obj)) {
return obj;
} else if (isPromise(obj)) {
return obj.then(Immutable);
} else if (Array.isArray(obj)) {
return makeImmutableArray(obj.slice());
} else if (obj instanceof Date) {
Expand Down
20 changes: 20 additions & 0 deletions test/Immutable.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,26 @@ var getTestUtils = require("./TestUtils.js");
})
});

it("makes the promise fulfillment value immutable, but not the promise itself", function() {
var promise = Promise.resolve([1,2,3]);
var wrappedPromise = Immutable(promise);

wrappedPromise.then(result => {
assert.isTrue(Immutable.isImmutable(result), 'The promise fulfillment value should be immutable');
assert.isFalse(Immutable.isImmutable(wrappedPromise), 'The promise itself should not be immutable');
});
});

it("doesn't wrap the promise rejection reason", function() {
var reason = new Error('foo');
var promise = Promise.reject(reason);
var wrappedPromise = Immutable(promise);

wrappedPromise.catch(catchedReason => {
assert.strictEqual(reason, catchedReason, 'The promise rejection reason should be left untouched');
});
});

it("doesn't fail when a function is defined on Array.prototype", function() {
Array.prototype.veryEvilFunction = function() {};
Immutable([]);
Expand Down

0 comments on commit c5af0b6

Please sign in to comment.