我试图从 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);
}
}
现在我需要获取 res
let dataObj;
getData().then(function (result) {
console.dir(result); // Ooops, the result is undefined
dataObj = result;
});
代码阻塞并等待结果,但我得到的是undefined而不是object
答案 0 :(得分:11)
这似乎是async/await
给你带来不多的情况之一。您仍然需要从异步函数返回结果,该函数将向调用者返回一个promise。你可以用以下的东西来做到这一点:
async function getData() {
try {
let res = await axios({
url: 'https://jsonplaceholder.typicode.com/posts/1',
method: 'get',
timeout: 8000,
headers: {
'Content-Type': 'application/json',
}
})
if(res.status == 200){
// test for status you want, etc
console.log(res.status)
}
// Don't forget to return something
return res.data
}
catch (err) {
console.error(err);
}
}
getData()
.then(res => console.log(res))
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
但是在这个例子中,由于你不需要在结果的实际函数中做很多事情,你可能最好只返回axios的承诺:
function getDataPromise() {
return axios({
url: 'https://jsonplaceholder.typicode.com/posts/1',
method: 'get',
timeout: 8000,
headers: {
'Content-Type': 'application/json',
}
})
.then(res => res.data)
.catch (err => console.error(err))
}
getDataPromise()
.then(res => console.log(res))
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
答案 1 :(得分:1)
我认为你对javascript的承诺和async / await没有正确理解。 请尝试这样:
#!/bin/sh
[ $# -eq 2 ] || { echo "Usage: ${0##*/} <file1> <file2>" 1>&2; exit 1; }
[ -r "$1" -a -r "$2" ] || { echo "$1 or $2: cannot read" 1>&2; exit 1; }
set -e
pr -s -t -m "$@" | \
awk '
{
offset = int(NF/2)
tab = ""
for (i = 1; i <= offset; i++) {
j = i + offset
if (NR == 1) {
if ($i != $j) {
printf "\nColumn name mismatch (%s/%s)\n", $i, $j > "/dev/stderr"
exit
}
printf "%s%s_1\t%s_2", tab, $i, $j
} else if ($i == $j) {
printf "%s=\t=", tab
} else {
printf "%s%s\t%s", tab, $i, $j
}
tab = "\t"
}
printf "\n"
}
'
async / await:
function getData(url, method) {
var ip = location.host;
return axios({
url: url,
method: method,
timeout: 8000,
headers: {
'Content-Type': 'application/json',
}
})
}
let dataObj;
let url = http() + ip + '/getData', method = 'post';
getData(url, method)
.then(function (result) {
console.dir(result);
dataObj = result;
})
.catch(function(error){
console.log(error);
});
答案 2 :(得分:0)
这不是你想听到的,而是
Async/Wait 的工作原理是“无论在维加斯发生什么 - 留在维加斯”。这意味着您无法传递在异步块之外使用阻塞 IO 调用的好处。
如果你想使用 async/await 来创建某种阻塞 IO 调用,它不会起作用,除非一个块调用者也在异步函数中,这通常不是这种情况。
async/wait 仅适用于您想要拥有一长串 IO 调用但整个链仍必须是非阻塞的。链内的个别调用可能会阻塞,但整个链不会。
示例
async fn(url) { //this is a non blocking function
let res = await axios.get("http://jsonservice1"); //blocking but only inside this function
let res2 = await axios.get(url+'?s='+res.data);//res.data is resolved already
return res2; //this how it returns results but it will not be resolved until .then is called what is effectively a callback
}
fn("google.com").then(R=>console.log('sorry I am not blocking '+R.data));