简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM