Inline (a)Wait for JavaScript Constructors

I have been working on some new code and found a need to make a series of calls to server-side PHP, where it would process data in a MySQL database, munch on some data and then return a result. I wanted to perform this operation inside a class constructor, so I could essentially do something like this:

const myObj = new MyClassToCallTheServer();
let someValue = myObj.doSomegthingWithTheServerData();
view raw inline1.js hosted with ❤ by GitHub

The problem is that a constructor in JavaScript cannot be declared async and you cannot place an await on your server call. So, something like this fails:

export default class MyClassToCallTheServer {
#internvalValue = null;
constrcutor() {
// this.#internalValue = await this.#callTheServer(); <– the await will fail to compile
this.#internalValue = this.#callTheServer();
}
doSomethingWithTheServerData = () => {
// the #internalValue is still null becasue we could not await in the constructor
return this.#internalValue;
}
#callTheServer = async() => {
// imagine some code here with a fetch command…
return serverData;
}
}
view raw inline2.js hosted with ❤ by GitHub

To get around this, I learned a new trick, so I thought I would share:

export default class MyClassToCallTheServer {
#internvalValue = null;
#loading = false;
constrcutor() {
this.#internalValue = this.#callTheServer();
}
doSomethingWithTheServerData = async () => {
while(this.#loading) await new Promise(resolve => setTimeout(resolve, 10));
// the #internalValue is not null because we waited
return this.#internalValue;
}
#callTheServer = async() => {
this.#loading = true;
// imagine some code here with a fetch command…
this.#loading = false;
return serverData;
}
}
view raw inline3.js hosted with ❤ by GitHub

Small modification to the original code above and done:

const myObj = new MyClassToCallTheServer();
let someValue = await myObj.doSomegthingWithTheServerData();
view raw inline4.js hosted with ❤ by GitHub

I threw post this together fairly quickly, but hopefully it makes sense. ☺️

Leave a Reply