使用await/async从axios获取响应

11 浏览
0 Comments

使用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); // 这里没问题,res中有JSON数据

return res;

}).catch(function (err) {

console.error(err);

})

}

catch (err) {

console.error(err);

}

}

现在我需要获取res

let dataObj;

getData().then(function (result) {

console.dir(result); // 哎呀,结果是undefined

dataObj = result;

});

这段代码是阻塞的,等待结果,但是我得到的是undefined而不是对象

0