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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const myObj = new MyClassToCallTheServer(); | |
let someValue = myObj.doSomegthingWithTheServerData(); |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
To get around this, I learned a new trick, so I thought I would share:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Small modification to the original code above and done:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const myObj = new MyClassToCallTheServer(); | |
let someValue = await myObj.doSomegthingWithTheServerData(); |
I threw post this together fairly quickly, but hopefully it makes sense. ☺️