将提取的 JSON 保存到变量中

Saving fetched JSON into variable

我正在尝试将 JSON 保存到一个变量中,但似乎我并不理解这里的所有内容。我以我喜欢的方式 JSON 一次出现在控制台中,但是在我尝试稍后再次调用它之后它只 returns 承诺。我怎样才能将 JSON 保存到变量中,以便以后可以使用 JSON 中的对象?

var jsondata = fetch(url).then(
    function(u){ return u.json();}
  ).then(
    function(json){
      console.log(json);
    }
  )
console.log(jsondata);
let jsondata;    
fetch(url).then(
        function(u){ return u.json();}
      ).then(
        function(json){
          jsondata = json;
        }
      )

基本上,一旦承诺用实际数据解决,您就需要分配 jsondata 变量。目前,您正在将整个承诺分配给您的 jsondata 变量,这不是您想要的。

获取 API 是基于 Promise 的,并且总是 return 一个新的 Promise 要么被解决要么被拒绝。您有多种选择 return 结果。

Async/Await

async function getData(url) {
  const response = await fetch(url);

  return response.json();
}

const data = await getData(url);

console.log({ data })

回调

function getData(url, cb) {
  fetch(url)
    .then(response => response.json())
    .then(result => cb(result));
}

getData(url, (data) => console.log({ data }))

另一种选择是使用回调作为参数,这样您就不会将变量暴露给全局范围。

function getFromAPI(url, callback){
  var obj;
  fetch(url)
    .then(res => res.json())
    .then(data => obj = data)
    .then(() => callback(obj))
 }

getFromAPI('https://jsonplaceholder.typicode.com/posts', getData);

function getData(arrOfObjs){
  var results = "";
  arrOfObjs.forEach( (x) => {
    results += "<p> Id: " + x.id + "<ul>"
    Object.keys(x).forEach( (p) => {
        results += "<li>" + (p + ": " + x[p]) + "</li>";
    });
    results += "</ul> </p> <hr>"
  })
  results += "";
  document.getElementById("myDiv").innerHTML = results;
}

http://jsfiddle.net/5gch2yzw/

您可以在 fetch 函数之外创建一个单独的函数来处理 json 数据,如下面的代码 fetch 函数将完整的 json 对象传递给另一个名为 "data_function" 的函数我们可以通过 "data_function".

继续处理 JSON 对象
//fetch function
fetch(url).then(
function(u){ return u.json();}
).then(
function(json){
data_function(json); //calling and passing json to another function data_function
}
)

//another functions
function data_function(data){
alert(data.length); 
}

最简单的方法是使用 async/await 方法。

只需将以下代码复制并粘贴到您的 chrome 开发控制台即可看到神奇之处:

async function githubUsers() {
            let response = await fetch('https://api.github.com/users')
            let users = await response.json()
            console.log(users)
    }

githubUsers()