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.
My html looks like:
<!DOCTYPE HTML>
<html>
<head>
<script src="https://test.com/script1.js"></script> // This contains the code which I shared
<script src="https://test.com/script2.js"></script> // This consumes the data. Hence code inside this should execute only after api call and assigment from the previous.
<script src="https://test.com/script3.js"></script> // This also consumes data from first import
</head>
<body>
<div id="body></div>
</body>
</html>
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 ...
... e.g. like that ...
The above shown/mentioned dynamic import gets achieved via the import syntax.