【问题标题】:how to print data outside fetch function?如何在获取功能之外打印数据?
【发布时间】:2018-12-05 23:11:12
【问题描述】:

我正在尝试创建一个不返回数据的 fetch 函数。

var url = "https://www.google.com/";
var testData = fetch(url, {
  method:'GET'
})
.then(function(resp){  
    return resp.json();
})
.then(function(data){
    return data;
});

console.log(testData); // here i want to print data

【问题讨论】:

    标签: javascript fetch


    【解决方案1】:

    Fetch 正在返回 Promise<Response>。您不能等到调用方代码中的 promise 完成。在here 中查看更多信息。你可以阅读更多关于 Promise 的内容here

    您可以在最后一次then 调用中打印结果:

    var url = "https://www.google.com/";
    fetch(url, {
      method:'GET'
    })
    .then(function(resp){  
        return resp.json();
    })
    .then(function(data){
        console.log(data); 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 2018-07-10
      相关资源
      最近更新 更多