Home > Enterprise >  How to store objects being returned from Async methods?
How to store objects being returned from Async methods?

Time:07-02

So I have two classes:

    public class Employee
    {
        public string status { get; set; }
        public EmployeeData[] data { get; set; }
        public string message { get; set; }
    }

    public class EmployeeData
    {
        public int id { get; set; }
        public string employee_name { get; set; }
        public int employee_salary { get; set; }
        public int employee_age { get; set; }
        public string profile_image { get; set; }
    }

And I am trying to call to a public API:

// using Newtonsoft.Json;
// using RestSharp;
public static async Task<Employee> getEmployeeData()
    {
        var client = new RestClient("http://dummy.restapiexample.com/api/v1/"); // Base url
        var request = new RestRequest("employees");
        var response = client.Execute(request);

        Employee result = null;
        string rawResponse = "";
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            rawResponse = response.Content;
            result = JsonConvert.DeserializeObject<Fact>(rawResponse); // JSON to C# Object
        }
        return result ;
    }

Then I am trying to store whatever is returned by getEmployeeData() in a variable called employee inside main:

static void Main(string[] args)
    {
        Employee employee = GetCatFact();
    }

BUT It says: "cannot implicitly convert type 'system.threading.tasks.task' to 'Employee'"

So how do I make it so that I can store getEmployeeData() inside the variable employee without changing getEmployeeData()?

CodePudding user response:

Mark your Main method as async one (available since C# 7.1) and call await on the GetCatFact (or getEmployeeData your question is a bit inconsistent):

static async Task Main(string[] args)
{
     Employee employee = await GetCatFact(); // or getEmployeeData
}

Related:

  1. asynchronous programming with async and await
  2. async modifier
  3. await operator

CodePudding user response:

getEmployeeData is async method, so you need to wait for result:

var employeeData = await getEmployeeData();

There is another option

var employeeData = getEmployeeData().Result;
  • Related