javascript - 如何使用 Fetch(不是 ajax)将 Promise 的解析存储到变量中

标签 javascript promise response fetch

以下代码运行良好,并将从网站获取的内容记录到控制台(输出一个已经为 json 格式的简单文件):

getData = url => {
  fetch(url)
    .then(response => {
      if (response.status !== 200) {
        console.log(
          "Looks like there was a problem. Status Code: " + response.status
        );
        return; //returns undefined!
      }

      // Examine the text in the response
      response.json().then(data => {
        console.log(data);
      });
    })
    .catch(function(err) {
      console.log("Fetch Error :-S", err);
    });
};

getData(urlToFetch); // logs to console the website call: a json file

我想将该提取的内容值存储在一个变量中供以后使用。

所以,当我改变时:

console.log(data);

到:

return data;

我得到一个未定义的。有帮助吗?

最佳答案

因为您在 getData 函数中使用 .catch,如果出现其他问题,您的函数也将解析 undefined。如果您想记录它,那么您需要将错误作为拒绝 promise 返回,以便调用者可以处理错误,而不是在 promise 解决时获得未定义的数据值。

你可以return Promise.reject("no 200 status code")表示拒绝,return response.json()表示resolve 如果你想添加 .then(x=>console.log(x)) 你仍然需要返回一些东西,否则调用 getData 的东西将解析为未定义:

getData = url => {
  fetch(url)
    .then(response => {
      if (response.status !== 200) {
        console.log(
          "Looks like there was a problem. Status Code: " + response.status
        );
        return Promise.reject(//reject by returning a rejecting promise
          "Looks like there was a problem. Status Code: " + response.status
        );
      }

      // Examine the text in the response
      response.json().then(data => {
        console.log(data);
        return data;//still need to return the data here
      });
    })
    .catch(function (err) {
      console.log("Fetch Error :-S", err);
      //return the reject again so the caller knows something went wrong
      return Promise.reject(err);
    });
};

getData(urlToFetch) // logs to console the website call: a json file
.then(
  x=>console.log("caller got data:",x)
)
.catch(
  e=>console.log("caller got error:",e)
);

关于javascript - 如何使用 Fetch(不是 ajax)将 Promise 的解析存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47765757/

相关文章:

c# - 在 asp.net/mvc 中的 Controller 内的操作中向 http 响应添加 header

Javascript 窗口写入回调

javascript - 如何重构我的 'view' 代码以显示每年的项目?

javascript - 我的 ES6 类方法是否应该返回一个 Promise,即使没有必要?

jsp - response.sendRedirect 不起作用

php - 高性能服务器上的 Apache 响应时间慢

用于输入时间的 Javascript 代码

javascript - 如何将本地时间与 setInterval() 一起使用?

javascript - 嵌套 promise Node js

javascript - 基于变量数组顺序执行异步方法