[英]Fetching return value from async function
I am trying to capture the response of two service calls within a function. 我试图捕获一个函数中两个服务调用的响应。 Got to know that async and await will solve this purpose and tried below.
知道异步和等待将解决此目的,并在下面进行了尝试。 Here inside async function ex - I am making a call to users, companies end point and console log is displaying perfect, but while retrieving the same value by calling the async function is giving Promise Pending.
在异步函数ex的内部-我正在打电话给用户,公司端点和控制台日志显示得很完美,但是通过调用异步函数检索相同的值却给出了Promise Pending。 I tried two options 1. by simply calling the async function - giving Promise Pending 2. by calling with await prefixed - giving await is a reserved word.
我尝试了两种选择:1.通过简单地调用async函数-给Promise Pending 2.通过在前缀为await的情况下进行调用-给await是保留字。
Please let me know how to capture the response from this... 请让我知道如何从中捕获响应...
const service = {
getUsers: () => axios.get(`http://localhost:3000/users`),
getCompanies: () => axios.get('http://localhost:3000/companies')
};
let ex = async () => {
let users = {};
let companies = {};
try {
users = await service.getUsers()
companies = await service.getCompanies()
console.log('Example ', {
users: users.data,
companies: companies.data
})
} catch (err) {
console.log(err);
}
return [{ users, companies}];
};
//let resp = await ex(); - giving await is a reserved word
// let resp = ex(); - giving Promise is pending..
console.log(resp);
All async
functions will always return a promise. 所有
async
功能将始终返回诺言。 If you return nothing, the function will return a promise for undefined
. 如果不返回任何内容,则该函数将返回
undefined
的promise。 Whatever you return will get wrapped up in a promise, which you need to await
or call then
on to access the value inside. 不管你会返回一个承诺,你需要得到包裹起来
await
或致电then
在里面访问值。
resp.then(console.log)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.