Controlling your own loop in n8n can get a little tricky because you have to use values from nodes that are in scope before the loop (initialized) AND within the loop (updated/incremented).
This makes use of the node.isExecuted
built in variable, and a JS ternary operator, to decide whether to use the initial value or the value from the last iteration of the loop. Examine the expression in the Increment Loop Var
node for details.
Key elements to making this work.
- All of the expressions must reference specific
Set
nodes by name (e.g.$('').first().json.page
). Nothing can just reference an attribute of the input (immediately previous node) (i.e. NOT$input.first().json.page
and NOT$json.page
). - The initial (first loop iteration) value must be set outside (previous to) the loop.
- There must be a second
Set
node within the loop that forwards the value back to theIncrement
Set
node, preferably using a different name (prevPage
) at the beginning of the loop, because theIncrement
node can’t refer to itself in an expression. - The increment node’s expression must have the ternary conditional clause (i.e.
(test) ? valueIfTrue : valueIfFalse
) to choose whether to use the initial value, or increment the value (prevPage
) forwarded from the otherSet
node within the loop.