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.