Search code examples
javascriptnode.jsfaunadb

Javascript Object returns empty when called


a piece of my code

const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results
const channelList = channels.each(function (page) {
  // Logs the page's contents,
  // for example: [ Ref(Collection("test"), "1234"), ... ]
  console.log(page);
});

works fine and behaves how it supposed to. however, when I try to call "channelList" from elsewhere in my code it returns {} The console.log in the first piece of code returns what it is supposed to as well so I dont think there is anything wrong with the first chunk of code.

Here is a piece of code where I attempt to call this object

  let options = {
    options: {
      debug: config.twitchConfig.options.debug
    },
    connection: {
      reconnect: config.twitchConfig.options.reconnect,
      secure: config.twitchConfig.options.secure
    },
    identity: {
      username: config.twitchConfig.connection.username,
      password: config.twitchConfig.connection.password
    },
    channels: [JSON.stringify(channelList)] // Attempt to call here, Returns {} (Empty object)
  };

Is there something I'm missing? is this even possible in the first place? if its not possible whats another method i can use to achieve the same result?

Edit: From what I can gather, channelList is based off of the page response, and it seems like the page response is private to that function and cannot be referenced outside of the function. what can I do to either make it referencable outside of the function or create a constant/variable that can be accessed outside of the function containing the same information


Solution

  • After much trial and error my answer was way simpler than me or anyone else I have spoken to thought.

    Here's a step by step guide on how to fix the problem yourself if you're experiencing the same issue as I was.

    1. Use a variable instead of a constant
    2. declare your variable before setting it by placing var channelList; somewhere above your code that sets it
    3. set the previously declared variable with a simple channelList = page
    4. console.log(channelList); just to make sure its all working
    5. Finally, call the variable where you want it, and voila! you have your variable properly called and it doesn't return {} or Undefined or [Object Object]