Ad

How To Call An Async Function In Non-Async Function

I am new to React Js, and trying to make an API call using fetch.

I have written a generic async function that I am using to API calls, to send requests to the API Endpoint. That function is being called in another class's function, that should parse the result and return the value to the parent function calling.

Here is my utility class with a function that calls the endpoint:

export default class RestUtil {
  getModel = async (model) => {
    let url = 'http://api.xyz.com/' + model;
    const apiCall = await fetch(url,
        {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': 'Bearer xyz'
            }
        });
    return  apiCall.json();
 }
}

Below is my React Component that is causing issues:

export default class MyComponent extends React.Component {
   componentDidMount() {
     this.populateUsersDropDown();
   }

   populateUsersDropDown() {
     let users = this.fetchUsers();
     // Here the `users` is undefined. <-------- Issue

     //Do some other work with users

     /*Populate users in 
                 the dropdown*/
   }

   fetchUsers() {
     new RestUtil()
         .getModel('users')
         .then(data => {
             /* Do some other work with data */
             return data;
         })
   }

}

Now I want the populateUsersDropDown() to wait for the fetchUsers() to complete it's then part and return the data and proceed. But I am receiving undefined in users variable. Wheres, in my then section, I am able to see the data.

Need some help in solving this please?

Ad

Answer

Your fetchUsers method does not return anything.

    async fetchUsers() {
     const users = await new RestUtil().getModel('users');

     return users;
   }

This should work

Ad
source: stackoverflow.com
Ad