How to call another function with in an Azure function

前端 未结 6 821
醉话见心
醉话见心 2021-02-07 00:21

I have written 3 functions as follows

  1. create users in db
  2. fetch users from db
  3. process users

In [3] function, I will call [2] functi

6条回答
  •  执笔经年
    2021-02-07 01:18

    All the previous answers are valid but, as was also mentioned in the comments, earlier this year (Q1/Q2 2018) the concept of Durable Functions has been introduced. In short, Durable Functions:

    ... lets you write stateful functions in a serverless environment. The extension manages state, checkpoints, and restarts for you.

    This effectively means that you can also now chain several Functions together. It manages state when it flows from Function A => B => C, if you would require this.

    It works by installing the Durable Functions Extension to your Function App. With that, you have some new context bindings available where, for example in C#, you can do something like (pseudo code):

    [FunctionName("ExpensiveDurableSequence")]
    public static async Task> Run(
        [OrchestrationTrigger] DurableOrchestrationTrigger context)
    {
        var response = new List();
    
        // Call external function 1 
        var token = await context.CallActivityAsync("GetDbToken", "i-am-root");
    
        // Call external function 2
        response.Add(await context.CallActivityAsync>("GetOrdersFromDb", token));
    
        return response;
    }
    
    [FunctionName("GetDbToken")]
    public static string GetDbToken([ActivityTrigger] string username)
    {
        // do expensive remote api magic here
        return token;
    }
    
    [FunctionaName("GetOrdersFromDb")]
    public static IEnumerable GetOrdersFromDb([ActivityTrigger] string apikey)
    {
        // do expensive db magic here
        return orders;
    }
    

    Some nice aspects here are:

    • The main sequence chains up two additional functions that are run after one another
    • When an external function is executed, the main sequence is put to sleep; this means that you won't be billed twice once an external function is busy processing

    This allows you to both run multiple functions in sequence of each other (e.g. function chaining), or execute multiple functions in parallel and wait for them all to finish (fan-out/fan-in).

    Some additional background reference on this:

    • Azure docs: Durable Functions overview
    • Azure Friday Introduction: 14m. video, with Chris Gillum and Scott Hanselman

提交回复
热议问题