在 Azure 逻辑应用中添加循环以重复执行操作或处理数组Create loops that repeat workflow actions or process arrays in Azure Logic Apps

若要在逻辑应用中处理数组,可以创建“Foreach”循环To process an array in your logic app, you can create a "Foreach" loop. 此循环会对数组中的每一项重复一个或多个操作。This loop repeats one or more actions on each item in the array. 有关“Foreach”循环可处理数组项数的限制,请参阅限制和配置For limits on the number of array items that "Foreach" loops can process, see Limits and configuration.

若要重复操作直到满足条件或状态发生变化,可以创建“Until”循环To repeat actions until a condition gets met or a state changes, you can create an "Until" loop. 逻辑应用运行循环内的所有操作,然后检查条件或状态。Your logic app runs all the actions inside the loop, and then checks the condition or state. 如果满足该条件,则循环将停止。If the condition is met, the loop stops. 否则,循环将继续进行。Otherwise, the loop repeats. 有关逻辑应用运行中“Until”循环数的限制,请参阅限制和配置For limits on the number of "Until" loops in a logic app run, see Limits and configuration.

Tip

如果你有接收数组的触发器并且希望针对每个数组项运行工作流,则可以使用 SplitOn 触发器属性“分离”该数组。If you have a trigger that receives an array and want to run a workflow for each array item, you can debatch that array with the SplitOn trigger property.

先决条件Prerequisites

Foreach 循环"Foreach" loop

“Foreach 循环”在每个数组项上重复一个或多个操作,且仅在数组上工作。A "Foreach loop" repeats one or more actions on each array item and works only on arrays. “Foreach”循环中的迭代并行运行。Iterations in a "Foreach" loop run in parallel. 但是,可以通过设置顺序“Foreach”循环一次运行一次迭代。However, you can run iterations one at a time by setting up a sequential "Foreach" loop.

使用“Foreach”循环时请注意以下事项:Here are some considerations when you use "Foreach" loops:

  • 在嵌套循环中,迭代总是按顺序运行,而不是并行运行。In nested loops, iterations always run sequentially, not in parallel. 若要对嵌套循环中的项目并行运行操作,请创建并调用子逻辑应用To run operations in parallel for items in a nested loop, create and call a child logic app.

  • 若要在每次循环迭代期间从变量操作获得可预测的结果,请按顺序运行这些循环。To get predictable results from operations on variables during each loop iteration, run those loops sequentially. 例如,当并发运行的循环结束时,递增变量、递减变量和附加到变量操作会返回可预测的结果。For example, when a concurrently running loop ends, the increment, decrement, and append to variable operations return predictable results. 但是,在并发运行循环的每次迭代期间,这些操作可能会返回不可预测的结果。However, during each iteration in the concurrently running loop, these operations might return unpredictable results.

  • “Foreach”循环中的操作使用 @item()Actions in a "Foreach" loop use the @item() 表达式来引用和处理数组中的每个项。expression to reference and process each item in the array. 如果指定了不在数组中的数据,则逻辑应用工作流将失败。If you specify data that's not in an array, the logic app workflow fails.

此示例逻辑应用会发送网站 RSS 源的每日摘要。This example logic app sends a daily summary for a website RSS feed. 该应用使用“Foreach”循环,为每一个新项发送电子邮件。The app uses a "Foreach" loop that sends an email for each new item.

  1. 使用 Outlook.com 或 Office 365 Outlook 帐户创建此示例逻辑应用Create this sample logic app with an Outlook.com or Office 365 Outlook account.

  2. 在 RSS 触发器与“发送电子邮件”操作之间,添加一个 Foreach 循环。Between the RSS trigger and send email action, add a "Foreach" loop.

    1. 若要在步骤之间添加循环,请将鼠标指针移到这些步骤之间的箭头上。To add a loop between steps, move your pointer over the arrow between those steps. 选择出现的加号 (+),然后选择“添加操作”。Choose the plus sign (+) that appears, then select Add an action.

      选择“添加操作”

    2. 在搜索框下,选择“所有”。Under the search box, choose All. 在搜索框中键入“for each”作为筛选器。In the search box, type "for each" as your filter. 在操作列表中选择此操作:“For each - 控制”From the actions list, select this action: For each - Control

      添加“For each”循环

  3. 现在,构建循环。Now build the loop. 在“添加动态内容”列表出现后,在“选择来自之前步骤的输出”下,选择“源链接”数组,这是来自 RSS 触发器的输出。Under Select an output from previous steps after the Add dynamic content list appears, select the Feed links array, which is output from the RSS trigger.

    从动态内容列表进行选择

    Note

    只能选择来自之前步骤的数组输出。You can select only array outputs from the previous step.

    所选数组现在显示在此处:The selected array now appears here:

    选择数组

  4. 若要对每个数组项执行操作,请将“发送电子邮件”操作拖到循环中。To run an action on each array item, drag the Send an email action into the loop.

    你的逻辑应用可能看起来如以下示例所示:Your logic app might look something like this example:

    向 Foreach 循环添加步骤

  5. 保存逻辑应用。Save your logic app. 若要手动测试逻辑应用,请在设计器工具栏上选择“运行”。To manually test your logic app, on the designer toolbar, choose Run.

Foreach 循环定义 (JSON)"Foreach" loop definition (JSON)

如果是在逻辑应用的代码视图中操作,可以改为在逻辑应用的 JSON 定义中定义 Foreach 循环,例如:If you're working in code view for your logic app, you can define the Foreach loop in your logic app's JSON definition instead, for example:

"actions": {
    "myForEachLoopName": {
        "type": "Foreach",
        "actions": {
            "Send_an_email": {
                "type": "ApiConnection",
                "inputs": {
                    "body": {
                        "Body": "@{item()}",
                        "Subject": "New CNN post @{triggerBody()?['publishDate']}",
                        "To": "me@contoso.com"
                    },
                    "host": {
                        "api": {
                            "runtimeUrl": "https://logic-apis-chinanorth.azure-apim.cn/apim/office365"
                        },
                        "connection": {
                            "name": "@parameters('$connections')['office365']['connectionId']"
                        }
                    },
                    "method": "post",
                    "path": "/Mail"
                },
                "runAfter": {}
            }
        },
        "foreach": "@triggerBody()?['links']",
        "runAfter": {},
    }
},

“Foreach”循环:顺序"Foreach" loop: Sequential

默认情况下,“Foreach”循环中的周期并行运行。By default, cycles in a "Foreach" loop run in parallel. 若要按顺序运行每个周期,请设置循环的“顺序”选项。To run each cycle sequentially, set the loop's Sequential option. 如果期望得出可预测结果的循环中具有嵌套循环或变量时,“Foreach”循环必须按顺序运行。"Foreach" loops must run sequentially when you have nested loops or variables inside loops where you expect predictable results.

  1. 在循环的右上角,选择省略号 (...) >“设置”。In the loop's upper right corner, choose ellipses (...) > Settings.

    在 Foreach 循环中,选择“...”>“设置”

  2. 在“并发控制”下,将“并发控制”设置转为“开启”。Under Concurrency Control, turn the Concurrency Control setting to On. 将“并行度”滑块移至“1”,然后选择“完成”。Move the Degree of Parallelism slider to 1, and choose Done.

    启用并发控制

如果在使用逻辑应用的 JSON 定义,则可以通过添加 operationOptions 参数来使用 Sequential 选项,例如:If you're working with your logic app's JSON definition, you can use the Sequential option by adding the operationOptions parameter, for example:

"actions": {
   "myForEachLoopName": {
      "type": "Foreach",
      "actions": {
         "Send_an_email": { }
      },
      "foreach": "@triggerBody()?['links']",
      "runAfter": {},
      "operationOptions": "Sequential"
   }
}

Until 循环"Until" loop

若要运行并重复操作直到满足条件或状态发生变化,请将这些操作放在“Until”循环中。To run and repeat actions until a condition gets met or a state changes, put those actions in an "Until" loop. 你的逻辑应用将首先运行循环内的所有操作,然后检查条件或状态。Your logic app first runs any and all actions inside the loop, and then checks the condition or state. 如果满足该条件,则循环将停止。If the condition is met, the loop stops. 否则,循环将继续进行。Otherwise, the loop repeats.

下面是可以在其中使用“Until”循环的一些常见场景:Here are some common scenarios where you can use an "Until" loop:

  • 调用某个终结点,直至获得想要的响应。Call an endpoint until you get the response you want.

  • 在数据库中创建记录。Create a record in a database. 等待该记录中的特定字段获得批准。Wait until a specific field in that record gets approved. 继续处理。Continue processing.

在每天上午 8:00,此示例逻辑应用都递增某个变量的值,直到该变量的值等于 10。Starting at 8:00 AM each day, this example logic app increments a variable until the variable's value equals 10. 然后,该逻辑应用会发送一封电子邮件来确认当前值。The logic app then sends an email that confirms the current value.

Note

这些步骤使用 Office 365 Outlook,但也可以使用逻辑应用支持的任何电子邮件提供商。These steps use Office 365 Outlook, but you can use any email provider that Logic Apps supports. 检查此处的连接器列表Check the connectors list here. 如果使用其他电子邮件帐户,则常规步骤保持不变,但 UI 外观可能稍有不同。If you use another email account, the general steps stay the same, but your UI might look slightly different.

  1. 创建空白逻辑应用。Create a blank logic app. 在逻辑应用设计器的搜索框下,选择“全部”。In Logic App Designer, under the search box, choose All. 搜索“定期”。Search for "recurrence". 从触发器列表中选择此触发器:“定期 - 计划”From the triggers list, select this trigger: Recurrence - Schedule

    添加“定期 - 计划”触发器

  2. 通过设置时间间隔、频率和天中的小时来指定触发器何时触发。Specify when the trigger fires by setting the interval, frequency, and hour of the day. 若要设置小时,请选择“显示高级选项”。To set the hour, choose Show advanced options.

    设置定期计划

    属性Property Value
    间隔Interval 11
    频率Frequency 日期Day
    在这些小时At these hours 88
  3. 在触发器下,选择“新建步骤”。Under the trigger, choose New step. 搜索“变量”,然后选择以下操作:“初始化变量 - 变量”Search for "variables", and select this action: Initialize variable - Variables

    添加“初始化变量 - 变量”操作

  4. 使用以下值设置变量:Set up your variable with these values:

    设置变量属性

    属性Property Value 说明Description
    名称Name LimitLimit 变量的名称Your variable's name
    类型Type IntegerInteger 变量的数据类型Your variable's data type
    Value 00 变量的起始值Your variable's starting value
  5. 在“初始化变量”操作下,选择“新建步骤”。Under the Initialize variable action, choose New step.

  6. 在搜索框下,选择“所有”。Under the search box, choose All. 搜索“until”,然后选择以下操作:“Until - 控制”Search for "until", and select this action: Until - Control

    添加“Until”循环

  7. 通过选择 Limit 变量和等于运算符构建循环的退出条件。Build the loop's exit condition by selecting the Limit variable and the is equal operator. 输入 10 作为比较值。Enter 10 as the comparison value.

    构建用于停止循环的退出条件

  8. 在循环中,选择“添加操作”。Inside the loop, choose Add an action.

  9. 在搜索框下,选择“所有”。Under the search box, choose All. 搜索“变量”,然后选择以下操作:“递增变量 - 变量”Search for "variables", and select this action: Increment variable - Variables

    添加用于递增变量的操作

  10. 对于“名称”,选择 Limit 变量。For Name, select the Limit variable. 对于“值”,输入“1”。For Value, enter "1".

    按增幅 1 递增“Limit”

  11. 在循环外部和循环下,选择“新建步骤”。Outside and under the loop, choose New step.

  12. 在搜索框下,选择“所有”。Under the search box, choose All. 查找并添加发送电子邮件的操作,例如:Find and add an action that sends email, for example:

    添加用于发送电子邮件的操作

  13. 根据提示登录到电子邮件帐户。If prompted, sign in to your email account.

  14. 设置电子邮件操作的属性。Set the email action's properties. Limit 变量添加到主题。Add the Limit variable to the subject. 这样,你可以确认变量的当前值满足你指定的条件,例如:That way, you can confirm the variable's current value meets your specified condition, for example:

    设置电子邮件属性

    属性Property Value 说明Description
    收件人To email-address@domain 收件人的电子邮件地址。The recipient's email address. 若要进行测试,请使用你自己的电子邮件地址。For testing, use your own email address.
    主题Subject “限制”的当前值为 LimitCurrent value for "Limit" is Limit 指定电子邮件主题。Specify the email subject. 对于本例,请确保包括 Limit 变量。For this example, make sure that you include the Limit variable.
    正文Body <email-content><email-content> 指定你要发送的电子邮件消息内容。Specify the email message content you want to send. 对于本例,输入你喜欢的任何文本。For this example, enter whatever text you like.
  15. 保存逻辑应用。Save your logic app. 若要手动测试逻辑应用,请在设计器工具栏上选择“运行”。To manually test your logic app, on the designer toolbar, choose Run.

    在你的逻辑开始运行后,你将收到一封包含指定内容的电子邮件:After your logic starts running, you get an email with the content that you specified:

    收到的电子邮件

防止无限循环Prevent endless loops

Until 循环具有默认限制,用于在发生下列任一条件时停止执行:An "Until" loop has default limits that stop execution if any of these conditions happen:

属性Property 默认值Default value 说明Description
CountCount 6060 在循环退出之前运行的最大循环次数。The highest number of loops that run before the loop exits. 默认值为 60 个周期。The default is 60 cycles.
超时Timeout PT1HPT1H 在循环退出之前运行循环的最大时间量。The most amount of time to run a loop before the loop exits. 默认值为一小时,并且是以 ISO 8601 格式指定的。The default is one hour and is specified in ISO 8601 format.

将针对每个循环周期评估超时值。The timeout value is evaluated for each loop cycle. 如果循环中的任何操作花费的时间超过超时限制,当前循环便不会停止。If any action in the loop takes longer than the timeout limit, the current cycle doesn't stop. 但是,由于不满足限制条件,因此下一个循环不会启动。However, the next cycle doesn't start because the limit condition isn't met.

若要更改这些默认限制,请在循环操作形状中选择“显示高级选项”。To change these default limits, choose Show advanced options in the loop action shape.

Until 定义 (JSON)"Until" definition (JSON)

如果是在逻辑应用的代码视图中操作,可以改为在逻辑应用的 JSON 定义中定义 Until 循环,例如:If you're working in code view for your logic app, you can define an Until loop in your logic app's JSON definition instead, for example:

"actions": {
   "Initialize_variable": {
      // Definition for initialize variable action
   },
   "Send_an_email": {
      // Definition for send email action
   },
   "Until": {
      "type": "Until",
      "actions": {
         "Increment_variable": {
            "type": "IncrementVariable",
            "inputs": {
               "name": "Limit",
               "value": 1
            },
            "runAfter": {}
         }
      },
      "expression": "@equals(variables('Limit'), 10)",
      // To prevent endless loops, an "Until" loop 
      // includes these default limits that stop the loop. 
      "limit": { 
         "count": 60,
         "timeout": "PT1H"
      },
      "runAfter": {
         "Initialize_variable": [
            "Succeeded"
         ]
      }
   }
}

此示例“Until”循环调用可创建资源的 HTTP 终结点。This example "Until" loop calls an HTTP endpoint, which creates a resource. 当 HTTP 响应主体返回 Completed 状态时,循环停止。The loop stops when the HTTP response body returns with Completed status. 为防止无限循环,该循环在发生下列任一条件时也会停止:To prevent endless loops, the loop also stops if any of these conditions happen:

  • 循环运行了 10 次(由 count 属性指定)。The loop ran 10 times as specified by the count attribute. 默认值为 60 次。The default is 60 times.

  • 循环已运行两小时(由 timeout 属性以 ISO 8601 格式指定)。The loop ran for two hours as specified by the timeout attribute in ISO 8601 format. 默认值为一小时。The default is one hour.

"actions": {
   "myUntilLoopName": {
      "type": "Until",
      "actions": {
         "Create_new_resource": {
            "type": "Http",
            "inputs": {
               "body": {
                  "resourceId": "@triggerBody()"
               },
               "url": "https://domain.com/provisionResource/create-resource",
               "body": {
                  "resourceId": "@triggerBody()"
               }
            },
            "runAfter": {},
            "type": "ApiConnection"
         }
      },
      "expression": "@equals(triggerBody(), 'Completed')",
      "limit": {
         "count": 10,
         "timeout": "PT2H"
      },
      "runAfter": {}
   }
}

获取支持Get support

后续步骤Next steps