3

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.

Igor F.
  • 2,649
  • 2
  • 31
  • 39
Chris Scott
  • 91
  • 1
  • 7
  • Reduce the code to *minimally* reproduce / demonstrate / illustrate the problem. The description "I don't know how to use the if statement to define the contactId variable" is unclear *and unrelated to the title and other content*. Both branches of the `if` are independent - and *any `let` defined inside is restricted to that if-block (and **unrelated** to async usages).* – user2864740 Jan 11 '20 at 19:51

2 Answers2

2

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!

Hemant Parashar
  • 3,684
  • 2
  • 16
  • 23
0

Move the declaration of contactId above the if/else so it's in scope for both.

For example:

function myfunc(x) {
  let contactId;

  if (x) {
    contactId = 12;
  } else {
    contactId = 42;
  }

  return contactId;
}
jarmod
  • 71,565
  • 16
  • 115
  • 122