如何使用来自函数的async-await返回来自异步函数的值? [英] How to return values from async functions using async-await from function?
本文介绍了如何使用来自函数的async-await返回来自异步函数的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从异步函数返回值? 我试图喜欢这个
How can I return the value from an async function? I tried to like this
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中,即
You cant await
something outside async
scope. To get expected result you should wrap your console.log
into async IIFE i.e
async function getData() {
return await axios.get('https://jsonplaceholder.typicode.com/posts');
}
(async () => {
console.log(await getData())
})()
Worked
示例.
有关 async/await
的更多信息
More information about async/await
由于axios
返回一个承诺,因此getData
函数可以省略async/await
,如下所示:
Since axios
returns a promise the async/await
can be omitted for the getData
function like so:
function getData() {
return axios.get('https://jsonplaceholder.typicode.com/posts');
}
然后像以前一样做
(async () => {
console.log(await getData())
})()
这篇关于如何使用来自函数的async-await返回来自异步函数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文