Javascript 如何使用函数的 async-await 从异步函数返回值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49938266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return values from async functions using async-await from function?
提问by King Rayhan
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());
it returns me this,
它返回给我这个,
Promise { <pending> }
采纳答案by The Reason
You cant awaitsomething outside asyncscope. To get expected result you should wrap your console.loginto async IIFE i.e
你不能await做一些超出async范围的事情。要获得预期的结果,您应该将您的内容包装console.log到异步 IIFE 中,即
async function getData() {
return await axios.get('https://jsonplaceholder.typicode.com/posts');
}
(async () => {
console.log(await getData())
})()
Workedsample.
Worked样本。
More information about async/await
有关的更多信息 async/await
Since axiosreturns a promise the async/awaitcan be omitted for the getDatafunction like so:
由于axios返回一个承诺,async/await因此可以getData像这样省略函数:
function getData() {
return axios.get('https://jsonplaceholder.typicode.com/posts');
}
and then do same as we did before
然后像我们以前一样做
(async () => {
console.log(await getData())
})()
回答by Pac0
your function getData will return a Promise.
您的函数 getData 将返回一个 Promise。
So you can either:
所以你可以:
awaitthe function as well to get the result. However, to be able to useawait, you need to be in anasyncfunction, so you need to 'wrap' this:async function callAsync() { var x = await getData(); console.log(x); } callAsync();(I named the function for sake of clarity, but in this scenario, one would rather use an anonymous function call; see TheReason's answer.)
await函数也可以得到结果。但是,为了能够使用await,你需要在一个async函数中,所以你需要“包装”这个:async function callAsync() { var x = await getData(); console.log(x); } callAsync();(为了清楚起见,我命名了该函数,但在这种情况下,人们宁愿使用匿名函数调用;请参阅 TheReason 的回答。)
or
或者
use the result as a normal Promise, which is what an async function returns.
You have to usethenwith a callback:getData().then(x => { console.log(x); }
将结果用作普通的 Promise,这是异步函数返回的结果。
您必须then与回调一起使用:getData().then(x => { console.log(x); }
回答by Meirion Hughes
The other answers have covered this fine; but I'd like to chip in and say get in the habit of creating and calling a mainfunction rather than run things in the global scope. i.e.
其他答案已经涵盖了这个罚款;但我想插一句,说养成创建和调用main函数的习惯,而不是在全局范围内运行。IE
async main(){
let result = await getData();
}
main().catch(console.log);
This is pretty clear to anyone reading your code that this is your app entry point
任何阅读您代码的人都非常清楚这是您的应用程序入口点

