Readable stream `_read` not called in test - ava

I have the following simplified ava test case. When I run it by ava _read() never get called (ONDATA is OK). On the other hand, when I run this test body (without assertions) as node script I always get _read() called as expected.
Probably I miss some key feature, please advice.
test('...', async t => {
class R extends stream.Readable {
_read() { console.log('READ'); }
}
const rs = new R();
rs.on('data', data => {
console.log('ONDATA ', data.toString());
});
rs.push(Buffer.from('data'));
// t.is(...)
})

I can't immediately recall in what scenario _read() should get called, but most likely your test ends before that happens. You have an async test but you don't seem to await anything. Try returning an explicit promise or otherwise use test.cb() so you can end the test with t.end().

Thanks! Essentially I messed up with readable stream callbacks and async test. The desired test looks like
test.cb('...', t => {
class R extends stream.Readable {
_read() {
console.log('READ');
// t.pass() or t.end() HERE
}
}
const rs = new R();
rs.on('data', data => {
// t.pass() or t.end() HERE
console.log('ONDATA ', data.toString());
});
rs.push(Buffer.from('data'));
})

Related

Save filereader result to variable for later use

I can't find simple answer, but my code is simple.
I tried something like that, but always when i try to console.log my testResult, then i always recieving null. How to save data from file correctly?
public getFile(
sourceFile: File
): string {
let testResult;
const file = sourceFile[0]
const fileReader = new FileReader();
fileReader.readAsText(file, "UTF-8")
fileReader.onloadend = (e) => {
testResult = fileReader.result.toString()
}
console.log(testResult)
return testResult
}
This problem is related to my other topics, main reason is i can't handle load json file, translate them and upload to user. If i can save this file outside onloadend, then i hope i can handle rest of them (other attempts failed, this one blocking me at beginning)
Your issue is quite classical and is related to the asynchronous operations. Function which you assign to the onloadend request is called only when loadend event fires, but the rest of code will not wait for that to happen and will continue execution. So console.log will be executed immediately and then return will actually return testResult while it is still empty.
Firstly, in order to understand what I just said, put the console.log(testResult) line inside of your onloadend handler:
fileReader.onloadend = (e) => {
testResult = fileReader.result.toString();
console.log(testResult);
}
At this point testResult is not empty and you may continue handling it inside this function. However, if you want your getFile method to be really reusable and want it to return the testResult and process it somewhere else, you need to wrap this method into a Promise, like this:
public getFile(
sourceFile: File
): Promise<string> {
return new Promise((resolve) => {
const file = sourceFile[0]
const fileReader = new FileReader();
fileReader.onloadend = (e) => {
const testResult = fileReader.result.toString();
resolve(testResult);
}
fileReader.readAsText(file, "UTF-8");
});
}
Now whereever you need a file you can use the yourInstance.getFile method as follows:
yourInstance.getFile().then(testResult => {
// do whatever you need here
console.log(testResult);
});
Or in the async/await way:
async function processResult() {
const testResult = await yourInstance.getFile();
// do whatever you need
console.log(testResult);
}
If you are now familiar with promises and/or async/await, please read more about here and here.

Mock mysql connection with Jest

Trying to test code that looks like this :
const mysql = require('mysql2/promise');
async myFunction () {
const db = await mysql.createConnection(options);
const results = await db.execute('SELECT `something` from `table`;');
await db.end();
// more code ...
}
I need to mock the the mysql connection in a way that will allow me to use whatever it returns to mock a call to the execute function.
I have tried mocking the whole mysql2/promise module but of course that did not work, since the mocked createConnection was not returning anything that could make a call to the execute function.
I also tried only mocking these 3 functions that I need instead of mocking the whole module, something like:
jest.mock('mysql2/promise', () => ({
createConnection: jest.fn(() => ({
execute: jest.fn(),
end: jest.fn(),
})),
}));
But that did not work too.
Any suggestions are highly appreciated.
I would approach this differently. When you feel you need to mock entire third-party libraries for testing, something is off in your application.
As a general best practice, you should always wrap third-party libraries. Check out this discussion for starters.
Basically the idea is to define your own interfaces to the desired functionality, then implement these interfaces using the third-party library. In the rest of your code, you would only work against the interfaces, not against the third-party implementation.
This has a couple of advantages
You can define the interfaces yourself. It will normally be much smaller than the entire third-party library, as you rarely use all functionality of that third-party library, and you can decide what's the best interface definition for your concrete use cases, rather than having to follow exactly what some library author dictates you.
If one day you decide you don't want to use MySQL anymore but move to Mongo, you can just write a Mongo implementation of your DB interface.
In your case, most importantly: You can easily create a mock implementation of your DB interface without having to start mocking the entire third-party API.
So how could this work?
First, define an interface as it would be most useful in your code. Perhaps, a DB interface for you could look like this:
interface Database<T> {
create(object: T): Promise<void>;
get(id: string): Promise<T>;
getAll(): Promise<T[]>;
update(id: string, object: T): Promise<void>;
delete(id: string): Promise<void>;
}
Now, you can develop your entire code base against this one Database interface. Instead of writing MySQL queries all across your code, when you need to retrieve data from 'table', you can use your Database implementation.
I'll just take an example ResultRetriever here that is pretty primitive, but serves the purpose:
class ResultRetriever {
constructor(private database: Database<Something>) {}
getResults(): Promise<Something[]> {
return this.database.getAll();
}
}
As you can see, your code does not need to care about which DB implementation delivers the data. Also, we inverted dependencies here: ResultReteriver is injected its Database instance. It does not know which conrete Database implementation it gets. It doesn't need to. All it cares about is that it is a valid one.
You can now easily implement a MySQL Database class:
class MySqlDatabase<T> implements Database<T> {
create(object: T): Promise<void> {...}
get(id: string): Promise<T> {...}
getAll(): Promise<T[]> {
const db = await mysql.createConnection(options);
const results = await db.execute('SELECT `something` from `table`;');
await db.end();
return results;
}
update(id: string, object: T): Promise<void> {...}
delete(id: string): Promise<void> {...}
}
Now we've fully abstracted the MySQL-specific implementation from your main code base. When it comes to testing, you can write a simple MockDatabase:
export class MockDatabase<T> implements Database<T> {
private objects: T[] = [];
async create(object: T): Promise<void> {
this.objects.push(object);
}
async get(id: string): Promise<T> {
return this.objects.find(o => o.id === id);
}
async getAll(): Promise<T[]> {
return this.objects;
}
update(id: string, object: T): Promise<void> {...}
delete(id: string): Promise<void> {...}
}
When it comes to testing, you can now test your ResultRetriever using your MockDatabase instead of relying on the MySQL library and therefore on mocking it entirely:
describe('ResultRetriever', () => {
let retriever: ResultRetriever;
let db: Database;
beforeEach(() => {
db = new MockDatabase();
retriever = new ResultRetriever(db);
});
...
});
I am sorry if I went a bit beyond the scope of the question, but I felt just responding how to mock the MySQL library was not going to solve the underlying architectural issue.
If you are not using/don't want to use TypeScript, the same logics can be applied to JavaScript.
There is a "brute-force" way if all you are really trying to do is to mock your MySQL calls. The following code is in TypeScript, but should be easily adaptable to regular JavaScript.
import * as mysql from "mysql2/promise";
import { mocked } from "ts-jest/utils";
jest.mock("mysql2/promise");
async function dbMethod(conn: mysql.Pool, field1Value: number): Promise<any> {
return await (conn.execute("SELECT field_1, field_2 FROM foo WHERE field_1=?",
[field1Value]) as Promise<mysql.RowDataPacket[]>);
}
describe("dbMethod", () => {
let mockDB: mysql.Pool;
beforeEach(() => {
mockDB = {
execute: jest.fn()
} as unknown as mysql.Pool;
});
it("should get something from database", async () => {
const mockExecute = mocked(mockDB.execute);
const testData = [{
field_1: 123,
field_2: 456
}];
mockExecute.mockResolvedValue([
[testData] as mysql.RowDataPacket[],
[]
]);
// Confirm results back from MySQL
await expect(dbMethod(mockDB, 123)).resolves.toEqual([[testData], []]);
// If you want, you can confirm MySQL execute was called as expected
expect(mockExecute).toHaveBeenCalledWith(
"SELECT field_1, field_2 FROM foo WHERE field_1=?",
[123]
);
});
});

Use CLS with Sequelize Unmanaged transactions

I am writing unit tests for my code and wish to use transactions to prevent any stray data between tests.
The code uses Sequelize ORM for all interactions with the database. Since changing the actual code is not an option, I would be using cls-hooked to maintain transaction context instead of passing transaction to all the queries. There is a problem, however. On reading the official documentation and trying to go about it, the above approach seems to only work for managed transactions.
So far, the test code looks somewhat like:
test("Test decription", async () => {
try {
await sequelize.transaction(async (t) => {
//Actual test code
});
} catch (error) {
//Do nothing if query rolled back
}
});
What I intend to achieve (for obvious reasons):
let t;
beforeEach(async () => {
t = await sequelize.transaction();
});
test("Test decription", async () => {
//Actual test code
});
afterEach(async () => {
await t.rollback();
});
Is this possible? If yes, any help in implementing this would be appreciated.
I'm having the same problem -- after much Googling, I found this closed issue where they indicate that unmanaged transactions aren't supported by design 🥲
It's true that Sequelize doesn't automatically pass transactions to queries when you're using unmanaged transactions. But you can manually set the transaction property on the CLS namespace, just like Sequelize does on a managed transaction:
https://github.com/sequelize/sequelize/blob/v6.9.0/lib/transaction.js#L135
namespace.run(() => {
namespace.set('transaction', transaction);
/* run code that does DB operations */
});
This is tricky for tests because describe() calls can be nested and each can have their own beforeAll()/afterAll() and beforeEach()/afterEach() hooks. To do this right, each before hook needs to set up a nested transaction and the corresponding after hook should roll it back. In addition, the test case itself needs to run in a nested transaction so that its DB operations don't leak into other tests.
For anyone from the future:
I was facing the above problem and found a way to fix it with a helper function and cls-hooked.
const transaction = async (namespace: string, fn: (transaction: Transaction) => unknown) => {
const nameSpace = createNamespace(namespace);
db.Sequelize.useCLS(nameSpace);
const sequelize = db.sequelize;
const promise = sequelize.transaction(async (transaction: Transaction) => {
try {
await fn(transaction);
} catch (error) {
console.error(error);
throw error;
}
throw new TransactionError();
});
await expect(promise).rejects.toThrow(TransactionError);
destroyNamespace(namespace);
};
What the above code does is creating a cls namespace and transaction that will be discarded after the test run, the TransactionError is thrown to ensure the entire transaction is always rolled back on each test run.
Usage on tests would be:
describe('Transaction', () => {
test('Test', async () => {
await transaction('test', async () => {
// test logic here
});
});
});

how to mock on global object in backstop.js/puppetter

So backstop.js provides ability to run custom script against underlying engine. I use puppeteer as an engine so I try to mock Date.now with 'onReadyScript':
page.evaluate('window.Date.now = () => 0; Date.now = () => 0;');
...
page.addScriptTag({
// btw `console.log` here is not executed, do I use it in wrong way?
content: 'Date.now = () => 0;'
});
...
page.evaluate(() => {
window.Date.now = () => 0;
Date.now = () => 0;
});
Last one, I think, is modifying Date in context of Node, not inside the puppeteer, but anyway tried that as well.
Nothing worked, script under the test still output real Date.now. Also I checked Override the browser date with puppeteer but it did not help me.
Yes, I know I'm able to skip particular selectors, but it does not always make sense(think about clock with arrows).
After trying onBeforeScript with evaluateOnNewDocument() it works for me. Complete script:
module.exports = async function (page, scenario) {
if (!page.dateIsMocked) {
page.dateIsMocked = true
await page.evaluateOnNewDocument(() => {
const referenceTime = '2010-05-05 10:10:10.000';
const oldDate = Date;
Date = function(...args) {
if (args.length) {
return new oldDate(...args);
} else {
return new oldDate(referenceTime);
}
}
Date.now = function() {
return new oldDate(referenceTime).valueOf();
}
Date.prototype = oldDate.prototype;
})
}
};
Reason: onReadyScript is executed when page under testing has already been loaded and executed. So code is bound to original Date by closure, not the mocked version.

async constructor functions in TypeScript?

I have some setup I want during a constructor, but it seems that is not allowed
Which means I can't use:
How else should I do this?
Currently I have something outside like this, but this is not guaranteed to run in the order I want?
async function run() {
let topic;
debug("new TopicsModel");
try {
topic = new TopicsModel();
} catch (err) {
debug("err", err);
}
await topic.setup();
A constructor must return an instance of the class it 'constructs'. Therefore, it's not possible to return Promise<...> and await for it.
You can:
Make your public setup async.
Do not call it from the constructor.
Call it whenever you want to 'finalize' object construction.
async function run()
{
let topic;
debug("new TopicsModel");
try
{
topic = new TopicsModel();
await topic.setup();
}
catch (err)
{
debug("err", err);
}
}
Readiness design pattern
Don't put the object in a promise, put a promise in the object.
Readiness is a property of the object. So make it a property of the object.
The awaitable initialise method described in the accepted answer has a serious limitation. Using await like this means only one block of code can be implicitly contingent on the object being ready. This is fine for code with guaranteed linear execution but in multi-threaded or event driven code it's untenable.
You could capture the task/promise and await that, but how do you manage making this available to every context that depends on it?
The problem is more tractable when correctly framed. The objective is not to wait on construction but to wait on readiness of the constructed object. These are two completely different things. It is even possible for something like a database connection object to be in a ready state, go back to a non-ready state, then become ready again.
How can we determine readiness if it depends on activities that may not be complete when the constructor returns? Quite obviously readiness is a property of the object. Many frameworks directly express the notion of readiness. In JavaScript we have the Promise, and in C# we have the Task. Both have direct language support for object properties.
Expose the construction completion promise as a property of the constructed object. When the asynchronous part of your construction finishes it should resolve the promise.
It doesn't matter whether .then(...) executes before or after the promise resolves. The promise specification states that invoking then on an already resolved promised simply executes the handler immediately.
class Foo {
public Ready: Promise.IThenable<any>;
constructor() {
...
this.Ready = new Promise((resolve, reject) => {
$.ajax(...).then(result => {
// use result
resolve(undefined);
}).fail(reject);
});
}
}
var foo = new Foo();
foo.Ready.then(() => {
// do stuff that needs foo to be ready, eg apply bindings
});
// keep going with other stuff that doesn't need to wait for foo
// using await
// code that doesn't need foo to be ready
await foo.Ready;
// code that needs foo to be ready
Why resolve(undefined); instead of resolve();? Because ES6. Adjust as required to suit your target.
Using await
In a comment it has been suggested that I should have framed this solution with await to more directly address the question as asked.
You can use await with the Ready property as shown in the example above. I'm not a big fan of await because it requires you to partition your code by dependency. You have to put all the dependent code after await and all the independent code before it. This can obscure the intent of the code.
I encourage people to think in terms of call-backs. Mentally framing the problem like this is more compatible with languages like C. Promises are arguably descended from the pattern used for IO completion.
Lack of enforcement as compared to factory pattern
One punter thinks this pattern "is a bad idea because without a factory function, there's nothing to enforce the invariant of checking the readiness. It's left to the clients, which you can practically guarantee will mess up from time to time."
If you take this position then how will you stop people from building factory methods that don't enforce the check? Where do you draw the line? For example, would you forbid the division operator because there's nothing stopping people from passing a zero divisor? The hard truth is you have to learn the difference between domain specific code and framework code and apply different standards, seasoned with some common sense.
Antecedents
This is original work by me. I devised this design pattern because I was unsatisfied with external factories and other such workarounds. Despite searching for some time, I found no prior art for my solution, so I'm claiming credit as the originator of this pattern until disputed.
Nevertheless, in 2020 I discovered that in 2013 Stephen Cleary posted a very similar solution to the problem. Looking back through my own work the first vestiges of this approach appear in code I worked on around the same time. I suspect Cleary put it all together first but he didn't formalise it as a design pattern or publish it where it would be easily found by others with the problem. Moreover, Cleary deals only with construction which is only one application of the Readiness pattern (see below).
Summary
The pattern is
put a promise in the object it describes
expose it as a property named Ready
always reference the promise via the Ready property (don't capture it in a client code variable)
This establishes clear simple semantics and guarantees that
the promise will be created and managed
the promise has identical scope to the object it describes
the semantics of readiness dependence are conspicuous and clear in client code
if the promise is replaced (eg a connection goes unready then ready again due to network conditions) client code referring to it via thing.Ready will always use the current promise
This last one is a nightmare until you use the pattern and let the object manage its own promise. It's also a very good reason to refrain from capturing the promise into a variable.
Some objects have methods that temporarily put them in an invalid condition, and the pattern can serve in that scenario without modification. Code of the form obj.Ready.then(...) will always use whatever promise property is returned by the Ready property, so whenever some action is about to invalidate object state, a fresh promise can be created.
Closing notes
The Readiness pattern isn't specific to construction. It is easily applied to construction but it's really about ensuring that state dependencies are met. In these days of asynchronous code you need a system, and the simple declarative semantics of a promise make it straightforward to express the idea that an action should be taken ASAP, with emphasis on possible. Once you start framing things in these terms, arguments about long running methods or constructors become moot.
Deferred initialisation still has its place; as I mentioned you can combine Readiness with lazy load. But if chances are that you won't use the object, then why create it early? It might be better to create on demand. Or it might not; sometimes you can't tolerate delay between the recognition of need and fulfilment.
There's more than one way to skin a cat. When I write embedded software I create everything up front including resource pools. This makes leaks impossible and memory demands are known at compile time. But that's only a solution for a small closed problem space.
Use an asynchronous factory method instead.
class MyClass {
private mMember: Something;
constructor() {
this.mMember = await SomeFunctionAsync(); // error
}
}
Becomes:
class MyClass {
private mMember: Something;
// make private if possible; I can't in TS 1.8
constructor() {
}
public static CreateAsync = async () => {
const me = new MyClass();
me.mMember = await SomeFunctionAsync();
return me;
};
}
This will mean that you will have to await the construction of these kinds of objects, but that should already be implied by the fact that you are in the situation where you have to await something to construct them anyway.
There's another thing you can do but I suspect it's not a good idea:
// probably BAD
class MyClass {
private mMember: Something;
constructor() {
this.LoadAsync();
}
private LoadAsync = async () => {
this.mMember = await SomeFunctionAsync();
};
}
This can work and I've never had an actual problem from it before, but it seems to be dangerous to me, since your object will not actually be fully initialized when you start using it.
Another way to do it, which might be better than the first option in some ways, is to await the parts, and then construct your object after:
export class MyClass {
private constructor(
private readonly mSomething: Something,
private readonly mSomethingElse: SomethingElse
) {
}
public static CreateAsync = async () => {
const something = await SomeFunctionAsync();
const somethingElse = await SomeOtherFunctionAsync();
return new MyClass(something, somethingElse);
};
}
I've found a solution that looks like
export class SomeClass {
private initialization;
// Implement async constructor
constructor() {
this.initialization = this.init();
}
async init() {
await someAsyncCall();
}
async fooMethod() {
await this.initialization();
// ...some other stuff
}
async barMethod() {
await this.initialization();
// ...some other stuff
}
It works because Promises that powers async/await, can be resolved multiple times with the same value.
I know it's quite old but another option is to have a factory that will create the object and wait for its initialization:
// Declare the class
class A {
// Declare class constructor
constructor() {
// We didn't finish the async job yet
this.initialized = false;
// Simulates async job, it takes 5 seconds to have it done
setTimeout(() => {
this.initialized = true;
}, 5000);
}
// do something usefull here - thats a normal method
useful() {
// but only if initialization was OK
if (this.initialized) {
console.log("I am doing something useful here")
// otherwise throw an error which will be caught by the promise catch
} else {
throw new Error("I am not initialized!");
}
}
}
// factory for common, extensible class - that's the reason for the constructor parameter
// it can be more sophisticated and accept also params for constructor and pass them there
// also, the timeout is just an example, it will wait for about 10s (1000 x 10ms iterations
function factory(construct) {
// create a promise
var aPromise = new Promise(
function(resolve, reject) {
// construct the object here
var a = new construct();
// setup simple timeout
var timeout = 1000;
// called in 10ms intervals to check if the object is initialized
function waiter() {
if (a.initialized) {
// if initialized, resolve the promise
resolve(a);
} else {
// check for timeout - do another iteration after 10ms or throw exception
if (timeout > 0) {
timeout--;
setTimeout(waiter, 10);
} else {
throw new Error("Timeout!");
}
}
}
// call the waiter, it will return almost immediately
waiter();
}
);
// return promise of the object being created and initialized
return a Promise;
}
// this is some async function to create object of A class and do something with it
async function createObjectAndDoSomethingUseful() {
// try/catch to capture exceptions during async execution
try {
// create object and wait until its initialized (promise resolved)
var a = await factory(A);
// then do something usefull
a.useful();
} catch(e) {
// if class instantiation failed from whatever reason, timeout occured or useful was called before the object finished its initialization
console.error(e);
}
}
// now, perform the action we want
createObjectAndDoSomethingUsefull();
// spaghetti code is done here, but async probably still runs
Use a private constructor and a static factory method FTW. It is the best way to enforce any validation logic or data enrichment, encapsulated away from a client.
class Topic {
public static async create(id: string): Promise<Topic> {
const topic = new Topic(id);
await topic.populate();
return topic;
}
private constructor(private id: string) {
// ...
}
private async populate(): Promise<void> {
// Do something async. Access `this.id` and any other instance fields
}
}
// To instantiate a Topic
const topic = await Topic.create();
Use a factory. That's the best practice for these cases.
The problem is that is tricky to define Typescript types for the factory pattern, especially with inheritance.
Let's see how to properly implement it in Typescript.
No inheritance
If you don't need class inheritance, the pattern is this:
class Person {
constructor(public name: string) {}
static async Create(name: string): Promise<Person> {
const instance = new Person(name);
/** Your async code here! **/
return instance;
}
}
const person = await Person.Create('John');
Class inheritance
If you need to extend the class, you will run into a problem. The Create method always returns the base class.
In Typescript, you can fix this with Generic Classes.
type PersonConstructor<T = {}> = new (...args: any[]) => T;
class Person {
constructor(public name: string) {}
static async Create<T extends Person>(
this: PersonConstructor<T>,
name: string,
...args: any[]
): Promise<T> {
const instance = new this(name, ...args);
/** Your async code here! **/
return instance;
}
}
class MyPerson extends Person {
constructor(name: string, public lastName: string) {
super(name);
}
}
const myPerson = await MyPerson.Create('John', 'Snow');
Extending the factory
You can extend the Create method too.
class MyPerson extends Person {
constructor(name: string, public lastName: string) {
super(name);
}
static async Create<T extends Person>(
this: PersonConstructor<T>,
name: string,
lastName: string,
...args: any[]
): Promise<T> {
const instance = await super.Create(name, lastName, ...args);
/** Your async code here! **/
return instance as T;
}
}
const myPerson = await MyPerson.Create('John', 'Snow');
Less verbose alternative
We can reduce the code verbosity by leveraging the async code to a non-static method, which won't require a Generic Class definition when extending the Create method.
type PersonConstructor<T = {}> = new (...args: any[]) => T;
class Person {
constructor(public name: string) {}
protected async init(): Promise<void> {
/** Your async code here! **/
// this.name = await ...
}
static async Create<T extends Person>(
this: PersonConstructor<T>,
name: string,
...args: any[]
): Promise<T> {
const instance = new this(name, ...args);
await instance.init();
return instance;
}
}
class MyPerson extends Person {
constructor(name: string, public lastName: string) {
super(name);
}
override async init(): Promise<void> {
await super.init();
/** Your async code here! **/
// this.lastName = await ...
}
}
const myPerson = await MyPerson.Create('John', 'Snow');
Aren't static methods bad practice?
Yes, with one exception: factories.
Why not return a promise in the constructor?
You can do that, but many will consider your code a bad pattern, because a constructor:
Should always return the class type (Promise<Person> is not Person);
Should never run async code;
You may elect to leave the await out of the equation altogether. You can call it from the constructor if you need to. The caveat being that you need to deal with any return values in the setup/initialise function, not in the constructor.
this works for me, using angular 1.6.3.
import { module } from "angular";
import * as R from "ramda";
import cs = require("./checkListService");
export class CheckListController {
static $inject = ["$log", "$location", "ICheckListService"];
checkListId: string;
constructor(
public $log: ng.ILogService,
public $loc: ng.ILocationService,
public checkListService: cs.ICheckListService) {
this.initialise();
}
/**
* initialise the controller component.
*/
async initialise() {
try {
var list = await this.checkListService.loadCheckLists();
this.checkListId = R.head(list).id.toString();
this.$log.info(`set check list id to ${this.checkListId}`);
} catch (error) {
// deal with problems here.
}
}
}
module("app").controller("checkListController", CheckListController)
Use a setup async method that returns the instance
I had a similar problem in the following case: how to instanciate a 'Foo' class either with an instance of a 'FooSession' class or with a 'fooSessionParams' object, knowing that creating a fooSession from a fooSessionParams object is an async function?
I wanted to instanciate either by doing:
let foo = new Foo(fooSession);
or
let foo = await new Foo(fooSessionParams);
and did'nt want a factory because the two usages would have been too different. But as we know, we can not return a promise from a constructor (and the return signature is different). I solved it this way:
class Foo {
private fooSession: FooSession;
constructor(fooSession?: FooSession) {
if (fooSession) {
this.fooSession = fooSession;
}
}
async setup(fooSessionParams: FooSessionParams): Promise<Foo> {
this.fooSession = await getAFooSession(fooSessionParams);
return this;
}
}
The interesting part is where the setup async method returns the instance itself.
Then if I have a 'FooSession' instance I can use it this way:
let foo = new Foo(fooSession);
And if I have no 'FooSession' instance I can setup 'foo' in one of these ways:
let foo = await new Foo().setup(fooSessionParams);
(witch is my prefered way because it is close to what I wanted first)
or
let foo = new Foo();
await foo.setup(fooSessionParams);
As an alternative I could also add the static method:
static async getASession(fooSessionParams: FooSessionParams): FooSession {
let fooSession: FooSession = await getAFooSession(fooSessionParams);
return fooSession;
}
and instanciate this way:
let foo = new Foo(await Foo.getASession(fooSessionParams));
It is mainly a question of style…
Create holder for promise status:
class MyClass {
constructor(){
this.#fetchResolved = this.fetch()
}
#fetchResolved: Promise<void>;
fetch = async (): Promise<void> => {
return new Promise(resolve => resolve()) // save data to class property or simply add it by resolve() to #fetchResolved reference
}
isConstructorDone = async (): boolean => {
await this.#fetchResolved;
return true; // or any other data depending on constructor finish the job
}
}
To use:
const data = new MyClass();
const field = await data.isConstructorDone();
Or you can just stick to the true ASYNC model and not overcomplicate the setup. 9 out of 10 times this comes down to asynchronous versus synchronous design. For example I have a React component that needed this very same thing were I was initializing the state variables in a promise callback in the constructor. Turns out that all I needed to do to get around the null data exception was just setup an empty state object then set it in the async callback. For example here's a Firebase read with a returned promise and callback:
this._firebaseService = new FirebaseService();
this.state = {data: [], latestAuthor: '', latestComment: ''};
this._firebaseService.read("/comments")
.then((data) => {
const dataObj = data.val();
const fetchedComments = dataObj.map((e: any) => {
return {author: e.author, text: e.text}
});
this.state = {data: fetchedComments, latestAuthor: '', latestComment: ''};
});
By taking this approach my code maintains it's AJAX behavior without compromising the component with a null exception because the state is setup with defaults (empty object and empty strings) prior to the callback. The user may see an empty list for a second but then it's quickly populated. Better yet would be to apply a spinner while the data loads up. Oftentimes I hear of individuals suggesting overly complicated work arounds as is the case in this post but the original flow should be re-examined.