我有兩個檔案,一個是從后端獲取資料,另一個是向回傳的資料添加功能和作業。之前,我是用 localStorage 做的,localStorage 速度很快,可以訪問任何檔案之外的元素,但是因為兩個檔案會同時加載,而后端的資料需要一些時間,檔案兩個功能一切都不起作用,我defer在兩個script標簽中都使用了。我想到的解決方案是如何在加載檔案 1 資料后加載檔案 2,但我不知道語法和所有要做的事情。任何幫助將不勝感激 :)
//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 >${productData.title}</h1>`
).join('');
});
}
```js
//File 2
const hye = document.querySelector('.hye');
hye....... // Do something with hye
uj5u.com熱心網友回復:
file 2在(for ex )中創建新函式processData()并將您的代碼包裝在其中。file 1完成后呼叫該函式fetch(根據您的要求在第二個.then()或適當的位置)
檔案 2
function processData() {
const hye = document.querySelector('.hye');
hye....... // Do something with hye
}
檔案 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 >${productData.title}</h1>`
).join('');
// Call function from file 2 from here
processData();
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/466637.html
標籤:javascript
上一篇:在React中訪問多個陣列的總和
下一篇:想知道這兩個幾乎相同的答案的區別
