Casebook02 · SuiteScript
A lookup on every line
A script looks up a field for each line of an order. Small orders are fine; a 200-line order runs out of governance or takes a minute to save.
- Casebook 02
- SuiteScript
What you notice
Orders with a handful of lines save normally. Large orders are slow, or fail with a usage limit error. The problem grows with the size of the order, so it often shows up months after go-live.
Why it happens
The script calls nlapiLookupField or loads a related record inside the line loop. Every line costs a server call and governance units. Fifty lines means fifty calls.
The fix in 2.1
Loop once to collect the IDs, run one search with anyof, and keep the results in a map. Then loop again and read from the map.
const ids = [];
for (let line = 0; line < count; line++) {
const id = rec.getSublistValue({ sublistId: 'item', fieldId: 'createdpo', line });
if (id) ids.push(id);
}
const dueDates = {};
search.create({ type: 'purchaseorder', filters: [['internalid', 'anyof', ids], 'AND', ['mainline', 'is', 'T']], columns: ['duedate'] })
.run().each((r) => { dueDates[r.id] = r.getValue('duedate'); return true; });
One or two lookups on a single record are fine. The problem is the lookup that scales with the number of lines.
What to check in your account
Look for nlapiLookupField, nlapiLoadRecord, search.lookupFields or record.load inside a for loop over sublist lines.