简体   繁体   中英

Accessing variable inside of forEach in mule

I have two queries

  1. Suppose if I declared two variables inside a forEach like flowVars.ABC and flowVars.DEF , how can I access those 2 variables outside that forEach block?

  2. And each variable has a JSON payload, how can I add those 2 variable's data into single JSON payload?

Can anyone assist me? I unable to access the variables inside of foreach and adding 2 JSON.

This is my sample code

<flow name="test">
        <foreach doc:name="For Each">
            <scatter-gather doc:name="Scatter-Gather">
                <set-variable variableName="ABC" value="#[payload]" mimeType="application/json" doc:name="ABC"/>
                <set-variable variableName="DEF" value="#[payload]" mimeType="application/json" doc:name="DEF"/>
            </scatter-gather>
        </foreach>
        <set-payload value="#[flowVars.ABC + flowVars.DEF]" mimeType="application/json" doc:name="adding 2 vars"/>
    </flow>

You need to understand how scoping works with foreach . Any variables set inside the foreach scope will NOT be available outside of that scope. However, variables set outside of the foreach scope (eg a set-variable before the foreach ) will be available inside the foreach scope. This should help you get around your issue. I'm taking out the scatter-gather because it really doesn't serve any purpose in your example:

<flow name="test">
    <set-variable variableName="ABC value="#[payload] mimeType="application/json" doc:name="ABC"/>
    <set-variable variableName="DEF value="#[payload] mimeType="application/json" doc:name="DEF"/>
    <foreach doc:name="For Each">
        <set-variable variableName="ABC" value="#[payload]" mimeType="application/json" doc:name="ABC"/>
        <set-variable variableName="DEF" value="#[payload]" mimeType="application/json" doc:name="DEF"/>
    </foreach>
    <set-payload value="#[flowVars.ABC ++ flowVars.DEF]" mimeType="application/json" doc:name="adding 2 vars"/>
</flow>

Beyond this, I'm not sure if your code is a simplification or not, but as it stands now there are a couple things that are questionable:

Why are you using a scatter-gather? If you don't really need to do multiple things asynchronously (like making calls to multiple services), it's just a complication in your code. Setting two vars doesn't qualify, in my opinion.

What is your code supposed to do? From my perspective it looks like you're just setting the payload to a duplicate of the last element in the original payload. If so you could just do this in a transformer:

%dw 2.0
output application/json
---
if (not isEmpty(payload))
  payload[-1] ++ payload[-1]
else
  []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM