0

I have a question with axios and async functions in general. I can get a return when using a synchronous functions. However, for my async, it returns a promise with fulfilled promise state and undefined promise result. I tried reading other SO questions but I cant seem to understand their explanation.

Sync:

function plusonefunc(var) {
    return var + 1;
}

let sum = plusonefunc(1); // returns 2

Async:

async function getvalue(var) {
    let data = {
        "var": var,
    }
    await axios({
        method: 'POST',
        crossDomain: true,
        url: '/url',
        headers: {
            "accept": "application/json",
            "Access-Control-Allow-Origin": "*"
        },
        data: data,
    })
    .then(response => {
        console.log(response);  // prints the desired value
        return response;        // return statement
    })
    .catch(error => {
        console.log(error)
    });
}

let response = getvalue("var");
console.log(response); // returns Promise {<pending>}[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: undefined 

How do I get the value of return response from the axios? Where should I put the return in the response?

Mr. Kenneth
  • 384
  • 1
  • 2
  • 14
  • Swap `await` for `return` (you can also lose the `async`) – Phil Aug 10 '21 at 04:14
  • Thank you for the response. After the changes, it now returns a promise but with object as the promise result but still a promise. How do I get the object only in let response = getvalue("var");? – Mr. Kenneth Aug 10 '21 at 04:24
  • `getValue("var").then(response => { /* access response here */ })` – Phil Aug 10 '21 at 04:26
  • Sorry. I should have been more specific. Yes I can get the value if I add a.then(response...) but I want the value of the `let response` to be the desired value which is an object, not a promise so that I can use the data outside the function. Not inside. Hope that I was more specific with my question. – Mr. Kenneth Aug 10 '21 at 04:27
  • If i was going to add the code inside the .then(), I would have done it inside the axios function instead. – Mr. Kenneth Aug 10 '21 at 04:28
  • You cannot convert an asynchronous action into a synchronous one. – Phil Aug 10 '21 at 05:28
  • Oh. I see. so I can only use the value inside the `.then()` ? Thank you for clarifying that one. – Mr. Kenneth Aug 10 '21 at 06:27

0 Answers0