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 usethen()
– 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
1 Answer
Reset to default 7Since "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
版权声明:本文标题:javascript - AsyncAwait func doesn't wait to console.log it's response - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741647019a2390244.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论