【问题标题】:ReferenceError: error is not defined, while trying to use function compositionReferenceError:错误未定义,同时尝试使用函数组合
【发布时间】:2017-09-15 06:34:02
【问题描述】:

我在nodejs中定义了两个简单的函数:

function findEntityDetailsAsIs(modelname, callback) {
     modelname.find({}, function(error, result) {
         if (error)
           callback (error, null);
         else {
           //console.log(result);
           callback (null, result);
         }
    });
};

这是我的第一个函数,另一个函数是

function printEntitydetails(error, entitydetails, callback) {
   console.log(entitydetails);
}

我正在尝试这样调用这些函数

findEntityDetailsAsIs(fieldLabel, printEntitydetails(error, entitydetails));

但是当我尝试运行这个函数调用它会抛出一个错误

ReferenceError: error is not defined

但错误就像我从回调传递的占位符对象一样。

 findEntityDetailsAsIs(fieldLabel, printEntitydetails(entitydetails));

我尝试在调用中跳过错误,但这次它给出了这个错误。

ReferenceError: entitydetails not  is not defined

据我所知,findEntityDetailsAsIs 应该为entitydetails 提供上下文,因为我提供了callback(null, result)

【问题讨论】:

  • 当你在函数名后面加上括号时,它会调用它并将它的输出作为回调传递。试试printEntitydetails.bind(null, error, entitydetails)

标签: javascript node.js express callback ecmascript-6


【解决方案1】:

你的函数findEntityDetailsAsIs期望得到回调函数,而不是它的执行结果。
您只需提供函数名称:

 findEntityDetailsAsIs(fieldLabel, printEntitydetails);

当您像以前一样运行它时,您会将printEntitydetails结果 传递给findEntityDetailsAsIs,而不是函数本身。由于该函数不返回任何内容,因此您会得到未定义

【讨论】:

  • OP 得到 ReferenceError: error is not defined。即使我怀疑同样的问题,但错误消息另有说明
  • 答案应该有效。如果您仍然收到错误意味着其他错误,我不确定,但可能是版本问题
  • 但是如果我必须使用另一个函数的执行结果,你能告诉我如何构造回调或者函数定义吗?例如function 1(somedata, function2(dataProcessedByfunction1, function3(dataProcessedByfunction2,))); 并且链可以长达 n 个函数。我的目标是将功能模块化,每个功能只做一个任务,然后创建一个功能链来完成整个过程。希望我对你很清楚
猜你喜欢
  • 2019-09-25
  • 2014-11-24
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
相关资源
最近更新 更多