如何从异步函数返回值? 我试着喜欢这样
const axios = require('axios'); async function getData() { const data = await axios.get('https://jsonplaceholder.typicode.com/posts'); return data; } console.log(getData());
它返回给我这个,
Promise { <pending> }
你的函数 getData 将返回一个。
所以你可以选择:
函数以及 await得到结果。然而,为了能够使用 await,您需要使用 async函数,因此您需要“包装”以下内容:
await
async
async function callAsync() { var x = await getData(); console.log(x); } callAsync();
(为了清晰起见,我命名了这个函数,但是在这个场景中,我们更愿意使用匿名函数调用; 请参见 TheReason 的 回答。)
或者
使用结果作为正常的承诺,这是异步函数返回的结果。 必须使用 then进行回调:
then
getData().then(x => { console.log(x); });
你不能把 async范围之外的东西 await。为了得到预期的结果,你应该把你的 console.log包装成异步 IIFE
console.log
async function getData() { return await axios.get('https://jsonplaceholder.typicode.com/posts'); } (async () => { console.log(await getData()) })()
样本。
更多关于 async/await的信息
async/await
因为 axios返回一个承诺,所以 async/await可以省略,对于 getData函数如下:
axios
getData
function getData() { return axios.get('https://jsonplaceholder.typicode.com/posts'); }
然后像以前那样做
(async () => { console.log(await getData()) })()
其他的答案已经涵盖了这个问题; 但是我想说的是,养成创建和调用 main函数的习惯,而不是在全局范围内运行。也就是说。
main
async function main(){ let result = await getData(); } main().catch(console.log);
这是非常清楚的任何人阅读你的代码,这是你的 应用程序入口点