最近在学习 axios 这个库,想通过这个库取得 json 数据然后做进一步处理,代码如下:
function getData(url) { var res; axios.get(url) .then(function (response) { res = response.data; }) .catch(function (error) { console.log(error); }); return res; } console.log(getData('https://yesno.wtf/api'));
返回的结果为 undefined,我知道这是因为 axios 采用的是异步操作,res 在 axios 获得返回数据前就已经由 getData()函数返回了,所以是 undefined。所以我很疑惑,到底怎样才能得到正确的返回值了?求问各位 JS 高手有没有比较优雅的实现方式?
![]() | 1 fay94 2017-08-18 21:28:05 +08:00 getData 应该返回一个 promise |
![]() | 2 mchl 2017-08-18 21:30:31 +08:00 via Android function getData(url) { axios.get(url) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.log(error); }); } getData('https://yesno.wtf/api'); |
![]() | 3 liuxin5959 2017-08-18 21:30:35 +08:00 你去学习一下 JS 的 async/await、Promise 相关的知识就知道该怎么做了。 |
![]() | 4 fay94 2017-08-18 21:31:43 +08:00 ``` function getData(url) { return axios.get(url) .then(function (response) { return response.data; }) .catch(function (error) { console.log(error); }); } getData('https://yesno.wtf/api') .then( data => { console.log(data) } ) ``` |
5 giuem 2017-08-18 22:10:21 +08:00 ES7 可以这样写 ``` (async () => { try { let { data } = await axios.get('https://yesno.wtf/api') console.log(data) } catch (err) { console.log(err) } })() ``` |
![]() | 6 sunjourney 2017-08-18 23:58:03 +08:00 是我就这么写 ``` axios.get(url).then(res => res.data).then(console.log).catch(console.log) ``` |
![]() | 7 sunjourney 2017-08-19 00:00:23 +08:00 或者 ```js const handleRespOnse= (res) { console.log(res.data) } const handleError = (err) { console.log(err) } axios.get(url).then(handleResponse).catch(handleError) ``` |
8 ccccccc 2017-08-19 00:23:03 +08:00 function getData(url) { return axios.get(url).then(function(res) { return res.data }) } getData('https://yesno.wtf/api').then(function(res) { console.log(res) }) |
![]() | 11 DCjanus 2017-08-19 11:12:36 +08:00 使用 TypeScript,即使编译到 ES5 也可以用 await |