I have the below code where I make an API call and store the response to window. This is done in order to access the value anywhere in the application. But since rest of the application is dependent on this code i want to make this synchronous, that is, rest of the JS should execute only after the api call is done and data is stored to global object. What is the best way to solve this?
Note: This is a sample of the use case. I can’t use methods like .then as this is first import in an HTML file having several JS file each of them being dependent on the response of this.
class GlobalConstants {
constructor() {
this.dynamicData = {};
this.getConfigData();
}
async getConfigData() {
try {
const configResponse = await fetch("https://jsonplaceholder.typicode.com/todos/1");
if (configResponse.status === 200) {
const dummyData = await configResponse.json();
this.dynamicUrl = dummyData;
} else {
throw new Error(`Config API threw ${formattedConfigResponse.status}`);
}
} catch (error) {
console.warn("Failed to fetch:", error);
}
}
}
window.globalConstants = new GlobalConstants();
console.log(globalConstants.dynamicData)
In the example, instead of consoling empty object it should ideally print the api response.
2
Answers
You could return a promise from the constructor and return the object (this) inside of it, after your async function has finished.
Short answer …
"There is no way around
async
/await
syntax, unless one wants to fall back to purely written promises."From both of my above comments …