0

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. 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.

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);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Suresh K
  • 21
  • 4
  • Nevermind, I got it. From async function, Promise will be returned and we need to check again by .then or .catch.. – Suresh K Oct 28 '17 at 04:05

1 Answers1

0

All async functions will always return a promise. If you return nothing, the function will return a promise for undefined. Whatever you return will get wrapped up in a promise, which you need to await or call then on to access the value inside.

resp.then(console.log)
skylize
  • 1,401
  • 1
  • 9
  • 21