我正在尝试从 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);
}
}
现在我需要获取 资源
let dataObj;
getData().then(function (result) {
console.dir(result); // Ooops, the result is undefined
dataObj = result;
});
代码正在阻塞并等待结果,但我得到的是 undefined 而不是 object
原文由 IgorM 发布,翻译遵循 CC BY-SA 4.0 许可协议
这似乎是
async/await
不会给你带来太多好处的情况之一。您仍然需要从异步函数返回一个结果,该结果将向调用者返回一个承诺。你可以用类似的东西来做到这一点:但在这个例子中,因为你不需要在实际函数中对结果做太多,你可能最好只返回 axios 的承诺: