小编Igo*_*orM的帖子

通过await/async获取axios的响应

我正试图从axios获取JSON对象

'use strict'

async function getData() {
    try {
        var ip = location.host;
        await axios({
            url: http() + ip + '/getData',
            method: 'POST',
            timeout: 8000,
            headers: {
                'Content-Type': 'application/json',
            }
        }).then(function (res) {
            console.dir(res); // we are good here, the res has the JSON data
            return res; 
        }).catch(function (err) {
            console.error(err);
        })
    }
    catch (err) {
        console.error(err);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我需要获取res

let dataObj;
getData().then(function (result) {
    console.dir(result); // Ooops, the result is undefined
    dataObj = result;
});
Run Code Online (Sandbox Code Playgroud)

代码阻塞并等待结果,但我得到的是undefined而不是object

javascript async-await axios

7
推荐指数
1
解决办法
2万
查看次数

标签 统计

async-await ×1

axios ×1

javascript ×1