Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 428
Joshua Soileau Avatar asked Nov 14 '18 22:11

Joshua Soileau


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))
like image 169
Nitish Narang Avatar answered Nov 14 '22 21:11

Nitish Narang