Reputation: 3015
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?
Upvotes: 7
Views: 14929
Reputation: 4184
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))
Upvotes: 7