Suresh K
Suresh K

Reputation: 21

Getting Promise pending ..- ES6

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 key word
   let resp = ex(); - Giving Promise pending
  console.log(resp);

Upvotes: 2

Views: 577

Answers (1)

JLRishe
JLRishe

Reputation: 101662

async/await doesn't magically allow you to perform asynchronous operations synchronously. Any way you cut it, you still wind up having to await the value at some point.

So you have two options.

  1. Put the stuff you want to do with the retrieved values in the asynchronous function:
let ex = async () => {
    let users = {};
    let companies = {};
    try {
        users =   await service.getUsers()
        companies = await  service.getCompanies()

        // DO STUFF WITH users AND companies HERE    

    } catch (err) {
      console.log(err);
    }
}
  1. Call .then on the promise that ex() returns and use the returned values:
ex().then(values => {
    console.log(values);
});

Upvotes: 2

Related Questions