【问题标题】:require scopes between required functions要求所需功能之间的范围
【发布时间】:2016-04-12 17:37:43
【问题描述】:

我正在尝试从导出的​​ js 文件中访问函数。 所以在我的主 app.js 文件之上,我需要这样的文件:

var api = require("./plugins/apis.js”);

我可以从这个文件中调用函数,但不能在其他 var 中调用 函数,即使我将 api 作为参数发送,例如

/**
 * @param access_token your access token from your instance settings page
 * @param [options] json object to be passed to the external web service. Can include any of 'context', 'verbose', 'n'
 * @param callback callback that takes 2 arguments err and the response body
 */


var getData = function (access_token, options, callback) {
   if(!callback) {
        callback = options;
        options = undefined;
    }
// do stuff
}

function init(api) {
    var information = getData(ACCESS_TOKEN, function (err, res) {
        init(api)
        // do stuff, but calls from apis.js functions not available.

我不想递归地要求这个,但我需要在我的 getData 函数中而不超出范围。 我不知道如何使用回调。有人可以解释如何使用回调并同时使用外部 apis.js 函数中的函数吗?

【问题讨论】:

  • 如果您从对require 的调用中删除.js,您会遇到同样的问题吗?所有这些代码都在app.js 中吗?
  • 我认为这样做没有问题。我们需要更多信息来了解您为什么会出现这种行为。能否提供getData函数和api.js模块的实现?

标签: node.js


【解决方案1】:

在 getData 的示例回调函数中,api 变量被回调自己的 api 参数覆盖。所以如果你想访问api你至少需要给它一个唯一的名字requireed:

var api = require("./plugins/apis”);

var information = getData(ACCESS_TOKEN, function (err, res, _api) {
  // do stuff
  // _api was passed here from getData()
  // api is still the object pulled in from your call to require()
});

【讨论】:

  • 我不知道为什么,但是 api.dostuff() 在 getData 中不起作用,尽管没有显示错误。如果我在 getData 之外使用完全相同的函数调用,它会按预期运行。这是因为我在调用同步函数吗?
  • 不看代码很难说。回调函数中的任何内容都会被执行吗?确保您的 getData 函数调用回调。如果您想开始一个新问题并在此处链接到它,我会看看。
猜你喜欢
  • 2014-12-20
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
  • 2012-07-01
  • 2019-11-03
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
相关资源
最近更新 更多