NODE.JS Twitch bot函数fetch完成工作,但返回未定义



所以我一直在寻找其他线程,似乎使用返回应该给父函数的值。但是我下面的代码总是返回Undefined

我感觉这是因为代码的时间。(同步和异步某事某事,仍在阅读此)

所以我的问题是,如果你们中有人能看到哪里出了问题,如果你能把我推向正确的方向(或者直接给我答案与文档链接以及)。

谢谢!

const tmi = require("tmi.js");
const fetch = require("node-fetch");
const doubleCommand = message.toLowerCase().split(" ");
// This function calls the code to be executed
if (doubleCommand[0] === "!shoutout" || doubleCommand[0] === "!so") {
console.log(isUser(doubleCommand[1], channel));
}
//This funktion checks to see if doubleCommand[1] is a existing user
function isUser(userLookUp, channel) {
fetch(
`https://api.twitch.tv/helix/users?login=${userLookUp.toLowerCase().trim()}`,
{
method: "GET",
headers: {
Authorization: `Bearer ${O_Token}`,
"Client-Id": C_ID
}
}
)
.then(res => res.json())
.then(res => {
if (res.data !== "undefined") { // Here i check to see if there was a user and if there was i check what game they are/were playing.
fetch(
`https://api.twitch.tv/helix/channels?broadcaster_id=${res.data[0].id}`,
{
method: "GET",
headers: {
Authorization: `Bearer ${O_Token}`,
"Client-Id": C_ID
}
}
)
.then(result => result.json())
.then(result => {
return res.data[0].game_name
});
} else {
}
});
}

我认为将您的代码转换为async/await模式将使其更具可读性,并帮助您跟踪问题。当然,你总是可以在你的代码中加入一些console.log语句(并且可能在完成所有操作之前发现它返回)。

代码从

开始
function doStuffThen() {
fetch(...).then(res => {
fetch(...).then(res => {
fetch(...).then(res => {
// etc etc
});
});
});
}

async function doStuffAsync() {
let data1 = await fetch(...);
let data2 = await fetch(...);
let data3 = await fetch(...);
return someResult;
}
最后,我不确定确切的问题在这里,但我绝对建议转向async/await并从那里调试。

最新更新