Используйте переменную после оператора if в функции asyn c - PullRequest
1 голос
/ 11 января 2020

Я пытаюсь создать функцию asyn c, в которой есть оператор if else. Все это должно быть внутри одной функции, потому что это внутри блока кода в zapier.

Я не могу использовать переменную, которую я определяю в операторе if, после инструкции. Оператор if, ожидающий до следующего вызова.

Я новичок в этом и promises, поэтому я не уверен, что делаю неправильно.

//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"
        }
      })
    });

Итак, я не знаю, как использовать оператор if для определения переменной contactId и заставить этот раздел ждать следующего вызова.

Спасибо за вашу помощь.

Ответы [ 2 ]

2 голосов
/ 11 января 2020

Проблема заключается в том, что let определяет область действия переменной contactId только внутри этого конкретного блока if или else, и, следовательно, вы получаете undefined при попытке войти / получить доступ к нему вне его области.

Переместите let contactId к отметке if / else выше, чтобы вы могли получить к ней доступ также снаружи, как это

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, 
   .
   .
   .
}

Прочтите это, чтобы лучше понять Что такое Разница между использованием "let" и "var"?

Надеюсь, это поможет!

0 голосов
/ 11 января 2020

Переместите объявление contactId над if / else, чтобы оно находилось в области видимости обоих.

Например:

function myfunc(x) {
  let contactId;

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

  return contactId;
}
...