js 新手求问 axios 中异步赋值的优雅姿势

2017-08-18 21:19:20 +08:00
 westworld

最近在学习 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 高手有没有比较优雅的实现方式?

2807 次点击
所在节点    问与答
12 条回复
fay94
2017-08-18 21:28:05 +08:00
getData 应该返回一个 promise
mchl
2017-08-18 21:30:31 +08:00
function getData(url) {

axios.get(url)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}

getData('https://yesno.wtf/api');
liuxin5959
2017-08-18 21:30:35 +08:00
你去学习一下 JS 的 async/await、Promise 相关的知识就知道该怎么做了。
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)
} )

```
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)
}
})()
```
sunjourney
2017-08-18 23:58:03 +08:00
是我就这么写
```
axios.get(url).then(res => res.data).then(console.log).catch(console.log)
```
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)
```
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) })
hjdtl
2017-08-19 08:57:49 +08:00
@giuem es6 也可以这么写了
giuem
2017-08-19 09:35:51 +08:00
@hjdtl Async/Await 是 ES7 的标准吧…
DCjanus
2017-08-19 11:12:36 +08:00
使用 TypeScript,即使编译到 ES5 也可以用 await
hjdtl
2017-08-19 13:06:48 +08:00
@giuem 这样吗... 我看阮一峰的书是归到 es6 里的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/384048

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX