我有两个文件是数组,我想从读取中加载它们。我有一个异步功能来获取文件:
async function getData(file) {
const data = await fetch(`./assets/resources/${file}.json`);
return await data.json()
}
然后在这里我将变量分配给此提取的返回值:let notes = getData("notes").then(res => res)
let pentagrama = getData("pentagrama").then(res => res)
但是我得到的是:from google chrome console
我实际上如何获得值(value)?
最佳答案
getData
的结果始终是解析为您的数据的Promise
。要访问这些值,可以使用async/await
:
(async () => {
let notes = await getData("notes");
let pentagrama = await getData("pentagrama");
// use them here
})();
另外,您可以使用
Promise.all
等待两个 promise 都解决,然后访问接收到的数据:let notesP = getData("notes");
let pentagramaP = getData("pentagrama");
Promise.all([noteP, pentagramaP]).then(res => {
let notes = res[0];
let pentagrama = res[1];
// use them here
});