node.js - 返回 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' }
解决方案
问题grabPopup
在于它没有暴露潜在的承诺,它应该是:
function grabPopup(fetchurl) {
return axios.get(fetchurl)...
}
这是这个流行问题的特例。无法同步访问结果,因为该函数是同步的。
它应该是:
grabPopup("https://pastebin.com/raw/0L1erTs1")).then(result => {
console.log(result);
});
推荐阅读
- reactjs - 未定义属性的问题(无法读取未定义的属性“查找”)
- html - 我的导航栏在手机中垂直堆叠。我希望它在一行中是水平的
- deep-learning - 使用带有自定义损失函数的 tensorboard.plugins.hparams api 进行超参数调整
- java - AndroidManifest.xml 中的谷歌搜索警告无法索引应用程序
- go - 重复消费 Kafka 消息的可能原因
- python - 基于另一列的行到列 好的,就是这样
- sql - Oracle中一列的前n个不同值
- c# - 通过C#获取AWS3目录中子目录中的文件名
- javascript - 关于复选框和单选按钮的问题
- reactjs - 当路由是子路由时,React 路由器不会触发 componentWillUnmount