Variable scope issue in Node.js

This topic was automatically generated from Slack. You can find the original thread here.

Neil Lovelace : Good Evening All,
I need some guidance.
I am making API calls and retrieving data without issue. I then try to pass that response data as a parameter into a function, but, I get an error stating that vendor is not defined. I’ve verified that my calls are working and that data is returned to the console.
Am I exceeding some limit or something? I’m not sure what’s happening.
See below code example:

// GET COMMITMENT INFORMATION
const commitment = await AXIOS.get(scpoURL, AXIOS_HDR(pro_token));
var cmtType = commitment.data.custom_fields["Subcontract template"].split(' ')[0]; // Long, Short, PSA, SAR
		
if (commitment.data.status == 'Out For Signature' || commitment.data.status == 'Approved'){

  // GET VENDOR INFORMATION
  var cmtVendor = commitment.data.vendor.id; // 7980013
  const vendor = await AXIOS.get(`${PRO_BASEURL}/rest/v1.0/vendors/${cmtVendor}?company_id=${companyID}`, AXIOS_HDR(pro_token));

  switch(resourceName){
	case 'Purchase Order Contracts':
		po();
	case 'Work Order Contracts':
		if(cmtType == 'PSA'){
			psa();
		} else {
			await sc(commitment.data, vendor.data, job.data, office.data, client.data[0], designer[0].data);
		}
  }
}
async function sc(commitment, vendor, job, office, client, designer){...}

Dylan Sather (Pipedream) : would you mind sharing your workflow with dylan@pipedream.com?

Neil Lovelace : Dylan… My Friend. Done.

Dylan Sather (Pipedream) : Are you familiar with the variable scope rules in JavaScript? See where you’re defining vendor in line 58 within the switch statement? That means vendor is only available within that switch block. So you actually can’t reference it outside that block.

Typically you’ll want to do something like:

let vendor;

at the top of your workflow. Then everywhere you need to set vendor, like on line 58, run:

vendor = ...

instead of const vendor =

Dylan Sather (Pipedream) : let me know if that makes sense or if you want me to share more resources on JS scoping rules

Neil Lovelace : I’m familiar with scope rules - not an expert obviously. HA!

Neil Lovelace : That’s odd because commitment.data pass without any problem and it is defined the same way as vendor.

Dylan Sather (Pipedream) : I would have to trace the code for that but did setting the declarations up top work OK?

Neil Lovelace : Yes. I took your suggestion and made edits. I’m debugging much further in my code now. Thanks!

Dylan Sather (Pipedream) : :thumbsup: