Node.js Twitch bot fetch function outputs undefined

I’ve been exploring some forums, and I’ve noticed that using the return statement should pass a value back to the parent function. However, the code I’ve shared below consistently returns undefined.

I suspect this might be linked to timing issues in my code, possibly related to sync and async processes (still diving deeper into this topic). Can anyone help identify the mistake in my code and perhaps point me in the right direction? Links to helpful documentation would be appreciated as well.

const tmi = require("tmi.js");
const fetch = require("node-fetch");
const commandComponents = message.toLowerCase().split(" ");

// Trigger the command execution
if (commandComponents[0] === "!shoutout" || commandComponents[0] === "!so") {
    console.log(checkUser(commandComponents[1], channel));
}

// Function to check if the user exists
function checkUser(usernameToCheck, channel) {
  fetch(
    `https://api.twitch.tv/helix/users?login=${usernameToCheck.toLowerCase().trim()}`,
    {
      method: "GET",
      headers: {
        Authorization: `Bearer ${O_Token}`,
        "Client-Id": C_ID
      }
    }
  )
    .then(response => response.json())
    .then(data => {
      if (data.data !== "undefined") {
        fetch(
          `https://api.twitch.tv/helix/channels?broadcaster_id=${data.data[0].id}`,
          {
            method: "GET",
            headers: {
              Authorization: `Bearer ${O_Token}`,
              "Client-Id": C_ID
            }
          }
        )
          .then(result => result.json())
          .then(channelData => {
            return data.data[0].game_name;
          });
      }
    });
}

Your function isn’t returning anything because the return statement is stuck inside promise callbacks. The checkUser function finishes running before the fetch requests complete, so it just returns undefined. You need to either return the promise chain or use async/await. Here’s the async/await fix:

async function checkUser(usernameToCheck, channel) {
  try {
    const response = await fetch(`https://api.twitch.tv/helix/users?login=${usernameToCheck.toLowerCase().trim()}`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${O_Token}`,
        "Client-Id": C_ID
      }
    });
    const data = await response.json();
    
    if (data.data.length > 0) {
      const channelResponse = await fetch(`https://api.twitch.tv/helix/channels?broadcaster_id=${data.data[0].id}`, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${O_Token}`,
          "Client-Id": C_ID
        }
      });
      const channelData = await channelResponse.json();
      return channelData.data[0].game_name;
    }
  } catch (error) {
    console.error('Error fetching user data:', error);
    return null;
  }
}

Now call it with await or .then() since it returns a promise.

the issue is that you’re returning inside a .then() but not returning the promise from checkUser. just add return before the fetch call and you’ll be good. also, don’t forget to handle the returned promise when you call checkUser!