【问题标题】:Fetching return value from async function从异步函数中获取返回值
【发布时间】:2018-04-09 14:51:46
【问题描述】:

我试图在一个函数中捕获两个服务调用的响应。知道 async 和 await 将解决这个目的并在下面尝试。在异步函数 ex 内部 - 我正在调用用户,公司端点和控制台日志显示完美,但是通过调用异步函数检索相同的值时,会出现 Promise Pending。我尝试了两个选项 1. 通过简单地调用 async 函数 - 给予 Promise Pending 2. 通过以 await 为前缀调用 - 给予 await 是一个保留字。

请让我知道如何捕获此响应...

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);

【问题讨论】:

  • 没关系,我明白了。从 async 函数中,Promise 将被返回,我们需要通过 .then 或 .catch..再次检查。

标签: javascript ecmascript-2017


【解决方案1】:

所有async 函数将总是返回一个承诺。如果您什么都不返回,该函数将返回一个对undefined 的承诺。无论您返回什么都将包含在一个 Promise 中,您需要 await 或调用 then 以访问其中的值。

resp.then(console.log)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2021-01-09
    • 2021-03-31
    • 1970-01-01
    相关资源
    最近更新 更多