【发布时间】: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