Optimize Javascript Code

Hello Community,

The javascript codes are missing to get the input from the last Item execution only.

The code is supposed to retrieve phone numbers from the last items executed since a split in batch node is set up before the execution

This workflow shared have to functionnalities.
The first part is a waterfall to enrich emails (everything works fine).

The second part is to enrich Phone Numbers, for this one I have some issues with it :


There is any optimization for the javascript to take on consideration only the item that is processing ? (last item) ? Or maybe the workflow structure ?

Information on your n8n setup

  • n8n version: Latest stable
  • **Running n8n via cloud **

Hi @TheG, I am sorry you’re having trouble. Your workflow seems quite complex and I am not sure I fully understand the problem. Are you expecting a different output from your Retrieve first Phonenumber Code node? Can you share an example of the input data for this node and the output you would like to see?

Hello @MutedJam,
Yes since there is a Split in batche so the workflow process item by item.

For both :

  • Aggregate PhoneNumbers items
  • Retrieve first Phonenumber

Should take on consideration the last item processing only, but that isn’t the case it run into some issues that it’s mixing the data results between different items.

The issue is since there are IF conditions, the code is taking on consideration the last execution, as you see in the screenshot below : the last execution for “Lusha” was 21, so the code is duplicating the phone number from execution 21 to all next executions.

I would love to optimize the code to take on consideration only the last execution counting from “Split In Batches” ?

Here’s the issue :

I assume that the code encounter the same issue with “Datagma” node.

Is that clear enough ? or you need more input ?

Got it, so the Aggregate PhoneNumbers items node isn’t returning what it should here. From the looks of it, this node doesn’t seem to read directly from your Split In Batches node, so I am not quite sure how this connection should work in your workflow.

In general, identifying the last run of a node within a loop is really tricky and only works by catching errors. On Merge multiple runs into one | n8n workflow template you can find a workflow which uses try/catch for such a job on the Code node (i indicates the last run in the example), but I very much suggest you avoid it if that’s possible (simply because it’s very confusing and not very elegant).

The current version of the Split in Batches node automatically returns all items as if they come from a single run on the “done” output which should help with that. If you can avoid the loop, n8n would then easily let you access the last input item by using $input.last() (documented here).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.