I am trying to make an asynchronous function and save it's response to a variable, then console.log that variable, but it is console.logging the response before the asynchronous function finishes.
import axios from 'axios';
async function getItems() {
const response = await axios.get(SOME_URL);
console.log('done', response);
return response;
}
const items = getItems();
console.log('items: ', items);
I would expect the logs to look like this:
// Expected result
done: {...result...}
items: {...items...}
But what I actually get is this:
// ACTUAL result
items: Promise {<pending>}
done: {...result...}
I want to wait until the request is complete to continue on below my call to getItems
.
What am I missing?
Since "getItems
" is async call so you will get the result in ".then" like below
import axios from 'axios';
async function getItems() {
const response = await axios.get(SOME_URL);
console.log('done', response);
return response;
}
getItems().then(items => console.log('items: ', items))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With