gpt4 book ai didi

javascript - 在函数中使用 fetch() 导致 "output not defined"

转载 作者:行者123 更新时间:2023-11-29 21:35:43 26 4
gpt4 key购买 nike

我已经使用 Zapier 几个星期了,和往常一样,随着我们构建每个功能,我们的需求变得更加复杂。因此,我当前在“Zapier 编写的代码”中遇到了一些 JavaScript 问题。

任何答案请注意:我本人和我手下的程序员团队都不是 JavaScript 专家,但我们确实理解大多数概念。

目标:仅当 javascript 的输入为真时才调用 fetch()。

问题:当代码中包含 fetch() 时,Zapier 总是返回“输出未定义”。

ReferenceError: output is not defined theFunction

即:整体代码结构没问题,我使用fetch()和返回处理的方式不行。

我已经尝试了无数种变体并利用了这里的一些很棒的帖子,但没有解决问题。

简化的代码如下所示:

 //This does the Fetch:
function doFetch(urlAddress) {
console.log("2. Doing Fetch");
return fetch(urlAddress)
.then(function(res) {
return res.text();
})
.then(function(response) {
//Hardcode a return.
console.log("3. Returning Response");
return response.json();
});
}

if (input.emailHasChanged == "true")
{
//Do Something
console.log("1. Updating Email");
doFetch(urlAddress)
.then(function(response) {
//Do something with Reponse.
console.log("4. Doing Something: ", response);
callback(null, response);
});
}
else
{
//Do Nothing
console.log("1. Not Updating email");
output = {id: 2};
}

我相信这是我从 fetch() 返回的方式或 JavaScript 的异步特性。

注意:Zapier 为我预定义了“输入”和“输出”变量。 'output' 最初为 Null,必须由代码设置一个值。

最佳答案

这个函数不正确:

//This does the Fetch:
function doFetch(urlAddress) {
console.log("2. Doing Fetch");
return fetch(urlAddress)
.then(function(res) {
return res.text();
})
.then(function(response) {
//Hardcode a return.
console.log("3. Returning Response");
return response.json(); // <-- response is an string. This method is not defined.
});
}

fetch() 解析为一个响应对象,该对象具有使用 .text().json()< 将主体读取为文本或 JSON 的方法分别。 .text() 的解析值是一个 string,它没有 .json() 方法。如果您只想将正文解析为 JSON,请使用:

//This does the Fetch:
function doFetch(urlAddress) {
console.log("2. Doing Fetch");
return fetch(urlAddress)
.then(function(res) {
return res.json();
});
}

关于javascript - 在函数中使用 fetch() 导致 "output not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34937442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com