Skip to content

Reviving async nested objects causes missing values #22

@lordofthelake

Description

@lordofthelake

When trying to revive custom objects that have as properties other custom objects, if the reviver functions are asynchronous, the outer object's reviver doesn't receive the nested revived value as an argument immediately, but it does after a timeout.

Simplified example:

class CustomObject { 
	constructor(value) {
		this.value = value;
	}
}

class CustomObjectWithNestedObject {
	constructor(custom) {
		this.custom = custom
	}
}

const tson = new Typeson().register([{
	CustomObject: {
		test: (v) => v instanceof CustomObject,
		replaceAsync: (v) => Typeson.Promise.resolve(v.value),
		reviveAsync: (v) => Typeson.Promise.resolve(new CustomObject(v))
	},
	CustomObjectWithNestedObject: {
		test: (v) => v instanceof CustomObjectWithNestedObject,
		replaceAsync: (v) => Typeson.Promise.resolve({ custom: v.custom }),
		reviveAsync: (v) => Typeson.Promise.resolve(new CustomObjectWithNestedObject(v.custom))
	}
}])

const custom = new CustomObject("Hello")
const customNested = new CustomObjectWithNestedObject(custom);

tson.encapsulateAsync(customNested)
	.then(encapsulated => tson.reviveAsync(encapsulated))
	.then(revived => console.log(revived.customNested)) // => undefined

Interestingly, when rewriting CustomObjectWithNestedObject's reviver using a setTimeout, the property appears, making the problem look like a race condition:

		// ...
		// This works! 
		reviveAsync: (v) => new Typeson.Promise((resolve, reject) => {
			setTimeout(() => {
				// By the time this is executed, v.custom appears on the object!
				resolve(new CustomObjectWithNestedObject(v.custom))
			}, 0);
		})

I have created a CodeSandbox with a reproduction here, with tests extracted from my code: https://codesandbox.io/s/typeson-async-bug-reproduction-prpp9

I hope this can be fixed soon, as this is an otherwise great library :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions