如何在axios中创建全局变量?

问题描述 投票:0回答:1

所以,我只是在学习有关axios的知识,并且一切看起来都不错,但是我想我对全局范围还不了解。这是我的代码:

axios.get('https://api.github.com/users/social-collab')
.then(function (response) {
console.log('Response: ', response.data);
const data = response.data;
return data;
})
.catch(function (handleError) {
console.log('Error: ', handleError);
},[]);

const myData = function(data) {

name = data.name; // This is the line with the error: data is not defined. But it is, isn't it?
return name;
}

console.log(myData(data));
javascript function variables axios global-variables
1个回答
0
投票

您不需要全局作用域,只需将另一个.then与函数myData链接在一起。

const myData = function(data) {
  name = data.name;
  console.log('name:', name)
  return name;
}

axios.get('https://api.github.com/users/social-collab')
.then(response => {
  const data = response.data;
  return data
})
.then(myData)
.catch(err => {
  console.log('Error: ', err);
})
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

从承诺中获取数据的方法是向.then提供一个函数。

© www.soinside.com 2019 - 2024. All rights reserved.