I am trying to create a async function that has an if else statement inside of it. All this needs to be within one function because this is within a code block in zapier.
I am unable to use a variable that I define within the if statement, after the statement. The if statement awaiting before the next call.
I am sort of new to this and promises so I'm not sure what I am doing wrong.
//Search For Contact (THIS IS ALL WRAPPED IN AN ASYNC FUNCTION CREATED BY ZAPIER)
const rawResponse = await fetch(`${baseURL}contacts?email=${agentFinalObject[0].agentEmail}`, {
method: 'GET',
headers: {
'Api-Token': token,
}
});
const content = await rawResponse.json()
//Here, the variable content is useable after this call.
//Found or No
if (content.contacts[0]) {
let contactId = await content.contacts[0].id
console.log(contactId) //Logging to the console here works.
} else {
//If no contact was found in the first call,
const createContact = await fetch(`${baseURL}contacts`, {
method: 'POST',
headers: {
'Api-Token': token,
},
body: JSON.stringify({
"contact": {
"email": agentFinalObject[0].agentEmail,
"firstName": agentFinalObject[0].agentFirst,
"lastName": agentFinalObject[0].agentLast,
"phone": agentFinalObject[0].agentPhone
}
})
});
const newContact = await createContact.json()
let contactId = await content.contacts.id
console.log(contactId) //Logging here works as well.
}
console.log(contactId)
//Logging here returns undefined error. Presumably because it runs before the if statement.
//Update Inspection Date. (I need to use contactId in the next call here. But it will be undefined!!!)
const updateDate = await fetch(`${baseURL}fieldValues`, {
method: 'POST',
headers: {
'Api-Token': token,
},
body: JSON.stringify({
fieldValue: {
contact: contactId, //Here it will still be undefined even tho the fetch is await.
field: 42,
value: "Black"
}
})
});
So, I don't know how to use the if statement to define the contactId variable and have that section wait for the following call.
Thanks for your help.
The issue is that let scopes the variable contactId only inside that particluar if or else block and hence you get undefined when you try to log/access it outside its scope.
Move the let contactId to above if/else statment so that you can access it outside as well like this
let contactId
if (content.contacts[0]) {
contactId = await content.contacts[0].id
console.log(contactId) //Logging to the console here works.
} else {
//If no contact was found in the first call,
.
.
.
}
Read this to have a better understanding What's the difference between using "let" and "var"?
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With