Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get response from axios with await/async

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

like image 315
IgorM Avatar asked Apr 04 '18 22:04

IgorM


People also ask

Can you use Axios with async await?

To use async and await with Axios in React, we can call axios in an async function. We call axios with the URL we want to make a GET request to. It returns a promise that resolves to an object with the data property set to the response data. So we use await to return the resolved value from the promise.

Is Axios get async?

Axios is a promise based HTTP client for the browser and Node. js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.

How do I get an Axios post response?

Axios Post Request The response is provided as a promise because Axios GitHub is promise-based. To obtain the response and catch any errors, we must utilize the then() and catch() functions.


1 Answers

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>
like image 159
Mark Avatar answered Sep 16 '22 15:09

Mark