【问题标题】:Use variable after if statement in an async function在异步函数中的 if 语句之后使用变量
【发布时间】:2020-01-11 19:46:37
【问题描述】:

我正在尝试创建一个内部包含 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 变量并让该部分等待以下调用。

感谢您的帮助。

【问题讨论】:

  • 减少代码以最少重现/演示/说明问题。 “我不知道如何使用if语句定义contactId变量”的描述不清楚与标题和其他内容无关if 的两个分支都是独立的 - 在内部定义的任何 let 都仅限于该 if 块(并且 与异步用法无关

标签: javascript asynchronous promise async-await


【解决方案1】:

问题是let 仅在特定的ifelse 块内限定变量contactId,因此当您尝试在其范围之外记录/访问它时会得到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, 
   .
   .
   .
}

阅读本文以更好地理解What's the difference between using "let" and "var"?

希望这会有所帮助!

【讨论】:

  • 啊错误的范围。早该想到的。现在工作。谢谢!
【解决方案2】:

contactId 的声明移到 if/else 上方,使其在两者的范围内。

例如:

function myfunc(x) {
  let contactId;

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

  return contactId;
}

【讨论】:

  • 是的,这也是解决方案。谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-01-08
  • 2012-10-31
  • 2011-10-01
  • 1970-01-01
  • 2022-11-17
  • 2018-01-26
相关资源
最近更新 更多