将提取的JSON保存到变量中

J H*_*tow 2 javascript json fetch

我正在尝试将JSON保存到变量中,但似乎我不了解这里的所有内容。我以自己喜欢的方式一次在控制台中显示JSON,但是稍后尝试再次调用它后,它仅返回promise。如何将JSON保存到变量中,以便以后可以在JSON中使用对象?

var jsondata = fetch(url).then(
    function(u){ return u.json();}
  ).then(
    function(json){
      console.log(json);
    }
  )
console.log(jsondata);
Run Code Online (Sandbox Code Playgroud)

Dra*_*scu 9

let jsondata;    
fetch(url).then(
        function(u){ return u.json();}
      ).then(
        function(json){
          jsondata = json;
        }
      )
Run Code Online (Sandbox Code Playgroud)

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


mar*_*ann 6

提取API基于Promise,并且将始终返回已解决或被拒绝的新Promise。您可以使用多个选项来存储结果。

变量分配

let data = [];

fetch(url)
    .then(response => response.json())
    .then(result => data.push(result));
Run Code Online (Sandbox Code Playgroud)

不幸的是,这可能有点怪异,因为您不知道何时填充数据变量。

诺言

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

getData(URL)
    .then(result => console.log(result));
Run Code Online (Sandbox Code Playgroud)

Anync&等待

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

    return response.json()
}

async function main() {
    const data = await getData(URL);

    console.log(data)
}
Run Code Online (Sandbox Code Playgroud)

如果您要问我,我会异步并等待。

  • `.then(result => result)` 是没有意义的。和`const result =等待response.json(); return result` 几乎是一样的。你可以简单地“返回response.json()” (3认同)