如何从异步函数返回值?我试图喜欢这个
const axios = require('axios'); async function getData() { const data = await axios.get('https://jsonplaceholder.typicode.com/posts'); return data; } console.log(getData());
它给了我,
Promise { <pending> }
您不能await超出async范围。为了获得预期的结果,您应该将其包装console.log到异步IIFE中,即
await
async
console.log
async function getData() { return await axios.get('https://jsonplaceholder.typicode.com/posts'); } (async () => { console.log(await getData()) })()
Worked 样品。
Worked
有关更多信息 async/await
async/await
由于axios返回一个Promise,因此async/await可以将其省略,getData如下所示:
axios
getData
function getData() { return axios.get('https://jsonplaceholder.typicode.com/posts'); }
然后像以前一样做
(async () => { console.log(await getData()) })()