Don*_*nor 3 javascript variables function global-variables axios
所以,我只是在学习 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));
Run Code Online (Sandbox Code Playgroud)
您不需要全局作用域,只需将另一个.then作用域与您的 function链接起来即可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);
})Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>Run Code Online (Sandbox Code Playgroud)
从 Promise 中获取数据的方法是向 提供一个函数.then。
| 归档时间: |
|
| 查看次数: |
7417 次 |
| 最近记录: |