admin管理员组

文章数量:1297030

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 plete to continue on below my call to getItems.

What am I missing?

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 plete to continue on below my call to getItems.

What am I missing?

Share asked Nov 14, 2018 at 22:17 Joshua SoileauJoshua Soileau 3,0259 gold badges44 silver badges52 bronze badges 3
  • 3 you should await getItems if you want to wait for the results – Ariel Commented Nov 14, 2018 at 22:18
  • 2 const items = await getItems() or use then() – Herohtar Commented Nov 14, 2018 at 22:18
  • 1 Using async/await doesn't magically make asynchronous behaviour synchronous. It's really just syntactic sugar for a function returning a promise; you still need to deal with that promise when you call the function, either by calling it from another async function or chaining thens. – jonrsharpe Commented Nov 14, 2018 at 22:26
Add a ment  | 

1 Answer 1

Reset to default 7

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

本文标签: javascriptAsyncAwait func doesn39t wait to consolelog it39s responseStack Overflow