'How to load file two after we get back the data from backend
I have two files, one is fetching data from the backend and the other is adding functions and working things to the data that came back. Earlier, I was doing this using localStorage and localStorage is fast and can access the elements outside of any file, but because both of the files will load at the same time, and the data from the backend will take some time, the file two functions and everything are not working, I am using defer in both of the script tags.
What I think of the solution is how to load the file 2 after the file 1 data has been loaded, but I am not aware of the syntax and all to do that.
Any help will be greatly appreciated :)
//File 1
function callProductDetails() {
const sendLocalId = JSON.parse(localStorage.getItem('mytest') ?? "[]");
fetch("/apps/selliy/localProduct", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(sendLocalId)
}).then(function (response) {
// The API call was successful!
return response.json();
}).then(function (data) {
console.log(data);
product_carousel_wrapper.innerHTML = data.map(productData =>
`<h1 class="hye">${productData.title}</h1>`
).join('');
});
}
```js
//File 2
const hye = document.querySelector('.hye');
hye....... // Do something with hye
Solution 1:[1]
Create new function in file 2 (for ex processData()) and wrap your code inside it. Call that function from file 1 after your fetch is completed (inside second .then() or at appropriate place as per your requirement)
File 2
function processData() {
const hye = document.querySelector('.hye');
hye....... // Do something with hye
}
File 1
function callProductDetails() {
const sendLocalId = JSON.parse(localStorage.getItem('mytest') ?? "[]");
fetch("/apps/selliy/localProduct", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(sendLocalId)
}).then(function (response) {
// The API call was successful!
return response.json();
}).then(function (data) {
console.log(data);
product_carousel_wrapper.innerHTML = data.map(productData =>
`<h1 class="hye">${productData.title}</h1>`
).join('');
// Call function from file 2 from here
processData();
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Karan |
