异步/等待功能不会等待console.log它的响应 [英] Async/Await func doesn't wait to console.log it's response
本文介绍了异步/等待功能不会等待console.log它的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作一个异步函数并将其响应保存到一个变量中,然后console.log该变量,但它是console.log在异步函数完成之前记录响应.
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...}
我想等到请求完成后再继续调用getItems
.
I want to wait until the request is complete to continue on below my call to getItems
.
我想念什么?
推荐答案
由于"getItems
"是异步调用,因此您将在".then"中获得结果,如下所示
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))
这篇关于异步/等待功能不会等待console.log它的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文