0

in order to use HTTPClient and post to a web service from my azure function app Cosmos DB trigger V1 I had to make the Function async which it is not by default,

Changing

 public static class Function1
    {
        [FunctionName("Function1")]
        public static void RunAsync([CosmosDBTrigger(

To

public static class Function1
    {
        [FunctionName("Function1")]
        public static async void RunAsync([CosmosDBTrigger(

Please note the async part in the second Function trigger definition

I need this because later on in the function I am using http client as follows and it must use await

HttpResponseMessage response = await httpClient.PostAsync("https://XXXXX", new StringContent(transaction.ToString(), System.Text.Encoding.UTF8, "application/json"));

Am I breaking the trigger by making it async or this is an accepted and supported change?

If not how can I change the use of my httpCLient to work within the trigger Function App?

NOTE: the code works as expected I am just worried it works by mistake so to day.

Jerry Liu
  • 17,282
  • 4
  • 40
  • 61
Matt Douhan
  • 2,053
  • 1
  • 21
  • 40

1 Answers1

1

No need to worry about the async modifier, it has no effect on how Azure Function works.

Azure Function assures trigger event is detected and corresponding parameters are populated before our self-defined code is executed. The async and await can only make difference to our self-defined code.

For example

Task<HttpResponseMessage> task = httpClient.PostAsync("https://XXXXX", new StringContent(transaction.ToString(), System.Text.Encoding.UTF8, "application/json"));

// Some synchronous code doesn't rely on the response
...

HttpResponseMessage response =  await task;

We usually create the task separately to take advantage of async. Function continues executing other code while waiting the http request task to complete. This is what we call asynchronous. After other code finished, we use await to make sure we get the desired response as there are no extra code to consume.

Your code awaits task to complete immediately with no code executed asynchronously, so it actually is executed in order as before.

Jerry Liu
  • 17,282
  • 4
  • 40
  • 61