我还是Java语言的新手。现在,我正在构建一个Web应用程序,我想在其中显示data.json文件中的项目并搜索这些项目。
我有一个fetchItems()
函数来获取data.json。之后,我index.html
用initItems()
函数显示中的项目。
问题是我也希望searchItems()
函数中的fetch调用中的那些“项目”也可用。我计划使用这些“项目”来过滤项目。不幸的是,我缺少了一些东西,这就是为什么console.log
insearchItems.js
会回馈undefined
。
我尝试了异步操作并等待其他操作,但都无法正常工作。
import { fetchItems } from "./src/js/fetchItems";
import { searchItems } from "./src/js/searchItems";
fetchItems();
searchItems();
export function fetchItems() {
return fetch("./src/data/data.json")
.then(response => response.json())
.then(items => initItems(items));
}
function initItems(items) {
for (let item of items) {
let appItem = document.createElement("app-item");
let appItems = document.getElementById("app-items");
appItems.appendChild(appItem);
appItem.setAttribute("name", item.name);
appItem.setAttribute("description", item.description);
}
}
export function searchItems(items) {
console.log(items);
}
我会这样做:
import { fetchItems } from "./src/js/fetchItems";
import { searchItems } from "./src/js/searchItems";
async function fetchAndSearch() {
const items = await fetchItems();
searchItems(items);
}
async function fetchItems() {
const response = await fetch("./src/data/data.json");
const items = await response.json();
initItems(items);
return items;
}
如果您以JavaScript开头,那么我认为async / await语法是可行的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句