For-each loop - Writer AI Studio

Overview

The For-each loop block iterates over a list or dictionary and executes a workflow for each item. The following variables are available in the workflow when iterating with the For-each loop block:

Example

The following example shows a For-each loop block that loops over a list of file IDs and makes an HTTP request to the Writer API to delete each file in the list by ID. It then sets a state variable to display a success message when it’s done.

In this example, the list of file IDs is a hardcoded list of strings. In a more realistic example, the list of file IDs would be returned from a previous block or stored in state, rather than hardcoded. In that case, you could use the environment variable such as @{payload} or @{state_element} to access the list in the Items field.

The For-each loop block iterates over the list of items in the Items field and executes the blocks that follow for each item. To reference the current item in the loop, you can use the environment variable @{item}. To reference the current item’s index in the list, you can use the environment variable @{itemId}. The HTTP request in this example uses the @{item} environment variable to reference the current file ID in the HTTP request’s URL field. When the For-each loop block is done, it moves to the next block connected to the Success connection point. In this example, the next block is a Set state block that sets a state variable to display a success message when it’s done.

Fields

Name Type Control Default Description Options Validation
Items Object Textarea [] The item value will be passed in the execution environment. It will be available at @, and its ID at @. You can use either a list or a dictionary. - -
Prefix Text - - If set, the item will be available at @ and the item id at @. - -

End states

Below are the possible end states of the block call.

Name Field Type Description
Loop - dynamic Connect the branch that you’d like to loop on. The branch plugged in here will be executed once per item.
Success - success The branch referenced executed successfully for each item.
Error - error The branch referenced has failed for at least one of the items.