首页 > 解决方案 > 返回 axios 数据未定义

问题描述

我正在尝试从 pastebin 链接中获取 json 数据并将其作为弹出窗口提供给我的电子应用程序,但是当尝试返回 axios 请求数据时,它出现未定义,console.log 也比 .then 更早地执行出于某种原因,我认为这与异步请求有关,但我还没有找到等待.then 的方法。

代码:

function grabPopup(fetchurl) {
  axios
    .get(fetchurl)
    .then(response => {
      // handle success
      //console.log(response.data);
      return response.data;
    })
    .catch(function(error) {
      // handle error
      console.log(error);
    });
}

console.log(grabPopup("https://pastebin.com/raw/0L1erTs1"));

控制台输出:

undefined
{ title: 'Test', message: 'Test2' }

标签: node.jselectronaxios

解决方案


问题grabPopup在于它没有暴露潜在的承诺,它应该是:

function grabPopup(fetchurl) {
  return axios.get(fetchurl)...
}

这是这个流行问题的特例。无法同步访问结果,因为该函数是同步的

它应该是:

grabPopup("https://pastebin.com/raw/0L1erTs1")).then(result => {
  console.log(result);
});

推荐阅读