无法从JSON文件获取的数据转换为新函数

娜塔莎卡特

我还是Java语言的新手。现在,我正在构建一个Web应用程序,我想在其中显示data.json文件中的项目并搜索这些项目。

我有一个fetchItems()函数来获取data.json。之后,我index.htmlinitItems()函数显示中的项目

问题是我也希望searchItems()函数中的fetch调用中的那些“项目”也可用我计划使用这些“项目”来过滤项目。不幸的是,我缺少了一些东西,这就是为什么console.loginsearchItems.js会回馈undefined

我尝试了异步操作并等待其他操作,但都无法正常工作。

index.js

import { fetchItems } from "./src/js/fetchItems";
import { searchItems } from "./src/js/searchItems";

fetchItems();
searchItems();

fetchItems.js

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);
    }
}

searchItems.js

export function searchItems(items) {
    console.log(items);
}

大卫·阿尔瓦雷斯

我会这样做:

index.js

import { fetchItems } from "./src/js/fetchItems";
import { searchItems } from "./src/js/searchItems";


async function fetchAndSearch() {
    const items = await fetchItems();
    searchItems(items);
}

fetchItems.js

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章