V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
westworld
V2EX  ›  问与答

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

  •  
  •   westworld · 2017-08-18 21:19:20 +08:00 · 2761 次点击
    这是一个创建于 2448 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    12 条回复    2017-08-19 13:06:48 +08:00
    fay94
        1
    fay94  
       2017-08-18 21:28:05 +08:00
    getData 应该返回一个 promise
    mchl
        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');
    liuxin5959
        3
    liuxin5959  
       2017-08-18 21:30:35 +08:00
    你去学习一下 JS 的 async/await、Promise 相关的知识就知道该怎么做了。
    fay94
        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)
    } )

    ```
    giuem
        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)
    }
    })()
    ```
    sunjourney
        6
    sunjourney  
       2017-08-18 23:58:03 +08:00
    是我就这么写
    ```
    axios.get(url).then(res => res.data).then(console.log).catch(console.log)
    ```
    sunjourney
        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)
    ```
    ccccccc
        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) })
    hjdtl
        9
    hjdtl  
       2017-08-19 08:57:49 +08:00
    @giuem es6 也可以这么写了
    giuem
        10
    giuem  
       2017-08-19 09:35:51 +08:00 via iPhone
    @hjdtl Async/Await 是 ES7 的标准吧…
    DCjanus
        11
    DCjanus  
       2017-08-19 11:12:36 +08:00
    使用 TypeScript,即使编译到 ES5 也可以用 await
    hjdtl
        12
    hjdtl  
       2017-08-19 13:06:48 +08:00
    @giuem 这样吗... 我看阮一峰的书是归到 es6 里的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   810 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 22:21 · PVG 06:21 · LAX 15:21 · JFK 18:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.