js 新手求问 axios 中异步赋值的优雅姿势 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
westworld
V2EX    问与答

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

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

    最近在学习 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     Solana     3320 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 29ms UTC 11:01 PVG 19:01 LAX 04:01 JFK 07:01
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86