了解 JavaScript 提取调用

Understanding JavaScript Fetch calls

我正在尝试将我的 API 从 XMLHttpRequest 迁移到 JavaScript 获取 API 调用。但是我无法得到想要的结果。

我的主脚本调用 API:

response = API.get_data()

我的API代码:

   var API = new function() {
    this.get_data  = function () 
    {fetch(url)
     .then(function(response) {
           if (response.status !== 200) {  
               console.log('Looks like there was a problem. Status Code: ' + response.status);  
               return;  
           }

           response.json().then(function(data) {  
                return data;
           });  
         })
         .catch(function(error) {
           console.log('There has been a problem with your fetch operation: ' + error.message);
          });
}

发生网络调用并检索到响应数据,但我无法在主脚本中获取响应。我该怎么做?

我是否需要使用回调函数来向主脚本传递响应数据?或者是否有任何我错过的预定义方法?

首先,您需要从 API 方法中 return fetch() 的结果。请注意,在 get_data 中,您调用 fetch() 但不会 return 结果。

return fetch(url).then(...)

其次,在您的主脚本中,您需要将结果视为 Promisefetch()get_data() 一个 ResponsePromiseget_data() 给主脚本一个 dataPromise

API.get_data().then(function(data) {
  // Same thing you did for fetch, you must do with get_data
})

如果你不明白为什么一定是这样,看看这个问题的华丽答案:How do I return the response from an asynchronous call?

可以在 promise 中访问响应,因此您的回调应该放在 then 正文中。

var API = new function() {
    this.get_data  = function () 
    {
       fetch(url)
         .then(function(response) {
           if (response.status !== 200) {  
               console.log('Looks like there was a problem. Status Code: ' + response.status);  
               return response.json();  
           }
         })
         .then(data => { 
           // do something with data here. you cannot return data because this is asynchronous
         }) 
         .catch(function(error) {
           console.log('There has been a problem with your fetch operation: ' + error.message);
          });
}