26

I want to return the response of axios but always the response that returned is undefined:

wallet.registerUser=function(data){
axios.post('http://localhost:8080/register',{
phone:data.phone,
password:data.password,
email:data.email
}).then(response =>{
  return response.data.message;
  console.log(response.data.message);
}).catch(err =>{
  console.log(err);
})
}

console.log(wallet.registerUser(data));

The console always logs as undefined. Is their any way returning this response.

Candy
  • 654
  • 2
  • 10
  • 24
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Mayank Shukla Aug 10 '17 at 18:12
  • 2
    Note: you cannot `console.log` after returning something. That's what's called _unreachable code_ — it can never be executed. – Karol Majewski Dec 26 '18 at 01:29
  • Its returning undefined because you aren't successfully calling whatever endpoint you think you are. Check the URL by running it in postman. You probably need to add some headers and may also need to disable certificate checking. If your environment needs a proxy, axios won't work. See my answer below. – Rodney P. Barbati Sep 12 '20 at 16:23

7 Answers7

34

console.log won't wait for the function to fully complete before logging it. This means that you will have to make wallet.registerUser asynchronous, there are two main ways to do this:

  1. Callback - this is when you pass a function as a parameter into your existing function which will be executed once your axios call has finished. Here is how it would work with your code:

    wallet.registerUser=function(data, callback){
      axios.post('http://localhost:8080/register',{
        phone:data.phone,
        password:data.password,
        email:data.email
      }).then(response =>{
        callback(response.data.message);
        console.log(response.data.message);
      }).catch(err =>{
        console.log(err);
      })
    }
    
    wallet.registerUser(data, function(response) {
      console.log(response)
    });
    
  2. Promise - The easiest way to do this is to put async in front of your function name. This will make anything returned from the function return in the form of a promise. This is how it would work in your code:

     wallet.registerUser=async function(data){
      axios.post('http://localhost:8080/register',{
        phone:data.phone,
        password:data.password,
        email:data.email
      }).then(response =>{
        return response.data.message;
        console.log(response.data.message);
      }).catch(err =>{
        console.log(err);
      })
    }
    
    wallet.registerUser(data).then(function(response) {
      console.log(response);
    });
    

Here is some more information on asynchronous functions:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

Sivabalan
  • 971
  • 2
  • 18
  • 43
Showard180
  • 405
  • 6
  • 6
7

You can use Promises:

I am new to react so you can give suggestions to me to improve my code.

For example I want to call checkVerified() function which is in other file:

Utils.js

export function checkVerified(val, values) {
    return new Promise((resolve, reject) => {
        axios
            .get(`${getInitialServerUrl}/core/check_verified/${val}/`)
            .then(res => {
                resolve(res)
            })
            .catch(err => reject(err))
    })
}

And I am calling this function from an another file:

someFile.js

const handleSubmit = e => {
        e.preventDefault();
        checkVerified(values.mobile, props)
            .then(res => {
               console.log(res);
         })
        .catch(err => console.log(err.response))
    }
Nikhil Bhardwaj
  • 562
  • 10
  • 18
1

You will need to wrap the call to axios in an async function. You can then return the response as you normally would.

As long as you call the wrapper method with await, you will be fine. Unfortunately, in order to call it with await, the calling method will also have to be marked async, and so on and so on, until every function in your application must be marked async and you will need to call ALL of your functions with await.

This is the magic and the beauty of the async / await keywords - utter garbage. You may see examples that create an async lambda to wrap the await axios, in an attempt to not have to refactor their entire app, but its not going to work.

So, the wrapper looks like the following...

async public post(URL, data) {

axios.post(URL, data)
    .then( (result) => {
        return result;
    });

}

If you are using typescript, that will add several more frustrating issues, such as how to cast an any to the type you want to return. I might suggest union types.

Anyway, good luck!

P.S. axios won't work if your environment requires using a proxy. In that case, and probably all others, use node-fetch - you will be up and running with node-fetch in a day. Axios will have you scratching your head a week later, wondering why its not working.

Rodney P. Barbati
  • 1,883
  • 24
  • 18
0

The main point here is to access the promise value. For that, we just need to log the response in the below format.

static getSearchAPI = () => {
return axios.post(URl);
}

getRestaurents() {
Helpers.getSearchAPI().then(function (response) {
  console.log(response.data);
})}
  • 1
    This answer does not address the actual question - that being how to return the response from an axios call. Syntactically, this answer is also unusable. – Rodney P. Barbati Sep 09 '20 at 19:21
  • Because we don't have any method to return the response, I thought this idea would be helpful. Here we can use some global variables to store the response and use it. – Parshuram Reddy Sep 11 '20 at 05:14
  • Global variable also not a good idea. You do have a method to return the response - see my answer below. – Rodney P. Barbati Sep 12 '20 at 16:28
0

I would implement the axios call like this with a compact syntax:

  myAxiosCall = async () => {
    return await axios.get('/the-url');
  }

It can be called like this:

myAxiosCall.then(data) {
   // Process the axios response
}
0
const fetch = async () => {
 try {
  const res = await axios.get(url)

  return res
 } catch (err) {
   throw err
 }
}

fetch().then((res) => {
  console.log(res)
}).catch((err) => {
  console.log(err)
})
Rafael
  • 1
  • 1
  • Please [edit] your answer to provide more information as to how the code you've provided works, what you have changed, etc. Code-only answers might solve the problem of the original asker but they don't help future readers understand the solution. – LW001 Aug 06 '23 at 15:28
-2

I used async and await methods and wrapped my axios call and function calling the axios call in these methods. I returned axios value as well as returned response object within it. I have shared the snippet in the below link.

Returning data from Axios API

Suvodeep Dubey
  • 109
  • 1
  • 6