Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用wait/async从axios获取响应_Javascript_Async Await_Axios - Fatal编程技术网

Javascript 使用wait/async从axios获取响应

Javascript 使用wait/async从axios获取响应,javascript,async-await,axios,Javascript,Async Await,Axios,我正在尝试从axios获取JSON对象 'use strict' async function getData() { try { var ip = location.host; await axios({ url: http() + ip + '/getData', method: 'POST', timeout: 8000, headers: {

我正在尝试从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;
});
现在我需要取res

'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;
});

代码正在阻塞并等待结果,但我得到的是未定义的对象,而不是对象

这似乎是
async/await
不能给您带来多少好处的情况之一。您仍然需要从异步函数返回一个结果,这将向调用者返回一个承诺。您可以通过以下方式实现:

异步函数getData(){ 试一试{ 让res=等待axios({ 网址:'https://jsonplaceholder.typicode.com/posts/1', 方法:“get”, 超时:8000, 标题:{ “内容类型”:“应用程序/json”, } }) 如果(res.status==200){ //测试你想要的状态等 console.log(res.status) } //别忘了还些东西 返回资源数据 } 捕捉(错误){ 控制台错误(err); } } getData() 。然后(res=>console.log(res))
我认为您没有正确理解javascript上的promise和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);
});
异步/等待:

function getData(url, method) {
    var ip = location.host;
    return axios({
        url: url,
        method: method,
        timeout: 8000,
        headers: {
            'Content-Type': 'application/json',
        }
    })
}
(async function(){
    let dataObj;
    let url = http() + ip + '/getData', method = 'post';
    try{
        const result = await getData(url, method);
        dataObj = result;
    } catch (error) {
        console.log(error);
    }
})();

这不是你想听的,而是

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));

您要么等待,要么承诺链。不是两者都有。这缺少一个
返回值
。如果您认为
位置,您可以
return
而不是
wait
ing。我想主机
可以抛出,但是
异步
在这里似乎根本没有必要。这不是异步/wait示例,所以对于第二个示例,外部函数返回一个承诺。因此,这是承诺中的承诺。是否有一种安全的方式使用async/await,以便它可以跨所有浏览器类型工作?另外,javascript中的async/await仅在Chrome中有效?@justdan23 async/await现在在所有现代浏览器中都可用。如果您需要支持IE,您将遇到更多的基本问题,因为async/await依赖于承诺,而IE不支持承诺。看看你是如何做到这一点的?var fetchedData=getData()我希望从API中获取一些数据,并将其传递给其他函数