Search code examples
typescriptes6-promise

How do I maintain Promise context between TypeScript classes?


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?

Link to the class in GitHub


Solution

  • 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.

    Here is the bug they pointed me to.