I have a TypeScript class with a class method that returns a promise:
GetSampleTrackingData() {
return new Promise<TrackingData>((resolve) => {
fs.readFile(path.resolve(__dirname, 'sim1.txt'), (err, data) => {
//Irrelevant code removed
resolve(foo);
});
});
}
When it's called, it throws the error ReferenceError: fs is not defined
. The code worked fine when not wrapped in the promise.
Essentially, the context is not being maintained when the promise is called. (it's being called from Express.js)
If it's relevant, I've tried a few different ways to import 'fs'.
How can I make the promise maintain the context?
I contacted the TypeScript team, and it turns out this is a TypeScript bug that occurs in 2.7.1. The fix should be in 2.7.2.
When you use the tsc -w
option, it is incorrectly removing some references when the code is used within a promise. The fix is to downgrade to 2.6, or use tsc
without the -w
option.