43

I'm trying to get JSON object from axios

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

Now I need to fetch the res

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

The code is blocking and waits for the result, but I'm getting undefined instead of object

2
  • 6
    You either do await, or a Promise chain. Not both. Commented Apr 4, 2018 at 22:14
  • 1
    This is missing a return. You could return instead of awaiting if you think location.host could throw, I guess, but async doesn’t seem necessary here at all. Commented Apr 4, 2018 at 22:15

3 Answers 3

75

This seems to be one of those cases where async/await doesn't buy you much. You still need to return a result from the async function, which will return a promise to the caller. You can do that with something like:

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>

But in this example, since you don't need to do much in the actual function with the result, you're probably better off just returning axios's promise:

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>

Sign up to request clarification or add additional context in comments.

5 Comments

so for 2nd example, the outer function returns a promise. So its a promise within a promise
Is there a safe way to use async/await so it will work across all browser types? AFAIK, async/await in javascript only works in Chrome?
@justdan23 async/await is in all modern browsers now. If you need to support IE, you'll have more basic problems because async/await depends on promises, which IE doesn't support. See can i use
How do achieve this ? var fetchedData = getData() I am looking to get some data from API and pass it on to some other function
@Mark I've been stuck for like 2 months due to this. Thanks man, you saved my life.
0

It is not what you would like to hear but

Async/Wait works on the principle "Whatever Happens in Vegas - Stays in Vegas". It means you could not pass benefits of using blocking IO calls outside of async block.

If you want to use async/await to create some kind of blocking IO call it would not work unless a block caller is also inside an async function what is not normally the case.

async/wait is only good if you want to have a long chain of IO calls but entire chain still MUST be non-blocking. Individual calls inside chain might be blocking but full chain not.

Example

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

Comments

0

Coming from ajax, I prefer modular approach. Data to be sent, function on success and function ‎on fail are separate from function using axios. Bellow sample code fetch user email against ‎user name form node.js and mysql at the backend. ‎

HTML: <button onclick=" testaxios();">TestAxios</button>‎

JS in browser:

var data = {
  username: "myusername"
}
async function testaxios() {
  try {
    let res = await axios({
      method: 'POST',
      data: data,
      url: '/testmysql',

    });
    if (res.status == 200) {
      success(res);
    };
  }
  catch (error) {
    fail(error);
  };
}

function success(res) {
  console.log(res.data[0][0].email);
}
function fail(error) {
  console.log(error);
}

JS in nodeJS at backend:

app.post("/testmysql", async function (req, res) {
try {
    let usrname = req.body.username;
    let em = await pool.query("SELECT email FROM users WHERE username = ?", usrname); 
    res.send(em);

} catch (err) {
    console.log(err);
} });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.