首页 > 解决方案 > Javascript 对象在调用时返回空

问题描述

我的一段代码

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);
});

工作正常并表现出应有的表现。但是,当我尝试从代码中的其他地方调用“channelList”时,它会返回 {} 第一段代码中的 console.log 也会返回它应该返回的内容,所以我认为第一块代码没有任何问题代码。

这是一段代码,我尝试在其中调用此对象

  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)
  };

有什么我想念的吗?这甚至可能吗?如果不可能,我可以使用另一种方法来达到相同的结果吗?

编辑:据我所知,channelList 是基于页面响应的,看起来页面响应是该函数私有的,不能在函数之外引用。我该怎么做才能使其在函数外部可引用,或者创建一个可以在包含相同信息的函数外部访问的常量/变量

标签: javascriptnode.jsfaunadb

解决方案


channelList 不是一个函数,更像是一个打印通道的函数的结果。所以在打印分配给它的内容之后就是结果。尝试将它假设为一个函数,然后调用它:

const channelList = ()=>{
 channels.each(function (page) {
  // Logs the page's contents,
  // for example: [ Ref(Collection("test"), "1234"), ... ]
  console.log(page);
});
};

channelList();

假设代码本身做你想做的,这应该做的工作


推荐阅读