How to Return Values from Async Functions Using Async-Await from Function

How to return values from async functions using async-await from function?

You cant await something outside async scope. To get expected result you should wrap your console.log into async IIFE i.e

async function getData() {
return await axios.get('https://jsonplaceholder.typicode.com/posts');
}

(async () => {
console.log(await getData())
})()

Working sample.

More information about async/await

Since axios returns a promise the async/await can be omitted for the getData function like so:

function getData() {
return axios.get('https://jsonplaceholder.typicode.com/posts');
}

and then do same as we did before

(async () => {
console.log(await getData())
})()

Return value from async / await function

async functions always return promises. async/await exists to simplify the syntax of working with promises, not to eliminate promises.

The code that's using your async function will need to call .then on the promise, or be an async function itself and await the promise.

this.getData()
.then(something => {

});
const something = await this.getData();

How to return a variable from an async function?

There are a few issues in your snippet including:

  • You are not returning price from your get_price function
  • You are not returning anything in your .then() call

Try the following snippet:

async function get_price(ticker) {
return await axios
.get(`https://marketwebsite.com/${ticker}`)
.then((res) => {
const $ = cheerio.load(res.data);
return $(".todays_price").map((index, element) => {
var value = $(element)
.find(".current_price")
.text()
.replace(/\s\s+/g, "");
return value;
});
})
.catch((err) => console.error(err));
}

get_price('ticker').then((res) => {
console.log(res); // Should print array of the values
});

I've used the jQuery .map method as it seems like you intended to return the values for each element.

I suggest going through the documentation on async await and promises on the MDN docs.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

async / await function and return value

The problem is in the second file. The line with your Axios should be modified as such:

return axios(config)
.then(function (res) {
console.log('AXIOS success');
console.log(res);
return res.data;
})
...

The axios call internally returns the value, but you never return it from googletranscribe

How to get the return value of a async function that returns a promise

async functions return a Promise which means their result is not immediately available.

What you need to do is either await the result of calling getAllProduct() function or chain a then() method call.

Looking at your code, i assume that you want to call getAllProduct() function after after your component is rendered. If that's the case, useEffect() hook is where you should call your function.

You could define and call your function inside the useEffect() hook and once the data is available, save that in the local state your component.

First define the local state of the component

const [products, setProducts] = useState([]);

Define and call the getAllProduct() function inside the useEffect() hook.

useEffect(() => {
const getAllProduct = async () => {
...

try {
let response = await axios(config);
allProduct = response.data.results;

// save the data in the state
setProducts(allProduct);

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

// call your async function
getAllProduct();
}, []);

Finally, inside the JSX, .map() over the products array and render the products in whatever way you want to render in the DOM.

return (
<div>
{ products.map(prod => {
// return some JSX with the appropriate data
}) }
</div>
);

How to return value in async await functions?

Async operations returns Promise objects. If you return a Promise from a function like in your example and pass it to a variable directly its type will be Promise. As a result you will be able to call then() and catch() methods on it.

const res = getNetwork();
res.then(
(responseData) = doSomething();
)

But if you store the return value with await prefix, then it will return the resolved data

const res = await getNetwork();
console.log(res); // res will be equal responseData above

But you must be careful about errors, if it throws an error your code will crash. I personally prefer to encapsulate this process in a try-catch block and if I catch an error ı return a null value. Example code below

async getResponse(): Promise<object> { // object can be changed with your response type
try {
const res = await getNetwork();
return res;
} catch (e) {
return null;
}
}

How to get value from async function?

An async function always returns a promise. The resolved value of that promise is whatever value the code in your function returns. So, to get the value out of that promise, you use either await or .then();

getFromDB().then(val => {
// got value here
console.log(val);
}).catch(e => {
// error
console.log(e);
});

There is no free lunch in Javascript. An value obtained asynchronously can only be returned from a function asynchronous (via callback or promise or other similar async mechanism).

Or, if the caller itself was an async function, then you could use await:

 async function someOtherFunc() {
try {
let val = await getFromDb();
console.log(val);
} catch(e) {
// error
console.log(e);
}
}


Related Topics



Leave a reply



Submit