所以,我只是在学习有关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));
您不需要全局作用域,只需将另一个.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
提供一个函数。