Async/Await func doesn't wait to console.log it's response

Viewed 11375

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?

1 Answers

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))
Related