加载json一次并使用内容文件OUTSIDE函数



对不起,有人能给我看代码并解释我,如何只加载一次json文件,并使用函数外的所有内容文件吗?

let jsonCompleto

fetch('uno.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
todo = data.length
console.log(todo)
jsonCompleto = data
console.log(jsonCompleto) // this return all the json file correctly

})
console.log(jsonCompleto) // this return undefined
// how can load only once the json file and use all content of json file OUTSIDE the function ?

您可以使用异步/等待

"use strict";
const myFetch = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1')
return response.json()
}
const myFunc = async () => {
data = await myFetch()

console.log(data)
}
myFunc()

你可以看到免费文档

最新更新