简体   繁体   English

当函数通常不需要任何参数时,试图理解 node.js 回调?

[英]Trying to understand node.js callback when the function normally doesn't expect any parameters?

I am trying to work with node.js and node-java and trying to get my head wrapped around some concepts, and in particular how to write async method calls.我正在尝试使用 node.js 和 node-java 并试图让我的头脑围绕一些概念,特别是如何编写异步方法调用。

I think that, for a function in Java, myclass.x():我认为,对于 Java 中的函数 myclass.x():

[In Java]: [在Java中]:

Z = myclass.x(abc);

And:和:

[In node.js/node-java]: [在 node.js/node-java 中]:

myclass.x(abc, function(err,data) {
//TODO
Z = data;});

In other words, the myclass.x function gets evaluated using the parameter abc, and if no error, then the result goes into "data" which is then assigned to Z.换句话说,myclass.x 函数使用参数 abc 进行评估,如果没有错误,则结果进入“数据”,然后分配给 Z。

Is that correct?那是对的吗?

Here's the thing (or one of the things) that I am confused about.这是我感到困惑的事情(或其中一件事)。

What happens if the function myclass.x() doesn't take any parameters?如果函数 myclass.x() 不带任何参数会发生什么?

In other words, it is normally (in Java) just called like:换句话说,它通常(在 Java 中)只是这样调用:

Z = myclass.x();

If that is the case, how should the node.js code look?如果是这样,那么 node.js 代码应该是什么样的?

myclass.x(, function(err,data) {
//TODO
Z = data;});

doesn't seem right, but:似乎不对,但是:

myclass.x( function(err,data) {
//TODO
Z = data;});

also doesn't seem correct.似乎也不正确。

So what is the correct way to code the node.js code in this case?那么在这种情况下编写 node.js 代码的正确方法是什么?

Thanks in advance!!提前致谢!!

Jim吉姆

EDIT 1: Per comments, I'm adding the specific code I'm working with is the last couple of commented out lines from this other question at:编辑 1:根据评论,我正在添加我正在使用的特定代码是来自另一个问题的最后几行注释:

node.js and node-java: What is equivalent node.js code for this java code? node.js 和 node-java:此 java 代码的等效 node.js 代码是什么?

These are the lines (commented out in that other question):这些是行(在另一个问题中注释掉):

var MyFactoryImplClass = java.import("oracle.security.jps.openaz.pep.PepRequestFactoryImpl.PepRequestFactoryImpl");

var result = myFactoryImplClass.newPepRequest(newSubject, requestACTIONString ,requestRESOURCEString , envBuilt)

I tried to make the last line use an async call:我试图让最后一行使用异步调用:

MyFactoryImplClass.getPepRequestFactory( function(err,data) {
    //TODO
    pepReqF1=data;})
javaLangSystem.out.printlnSync("Finished doing MyFactoryImplClass.getPepRequestFactory() and stored it in pepReqF1 =[" + pepReqF1 + "]");

But the output was showing the value of that pepReqF1 as "undefined".但是输出显示 pepReqF1 的值是“未定义”。

If calling the method with one parameter and a callback is:如果使用一个参数和回调调用方法是:

myclass.x(abc, function(err, data) {
  // ...
});

Then calling a method with only a callback would be:然后调用一个只有回调的方法将是:

myclass.x(function(err, data) {
  // ...
});

The function(err, data) { } part is just a normal parameter just like abc . function(err, data) { }部分只是一个普通参数,就像abc一样。 In fact, you can pass a named function with:实际上,您可以通过以下方式传递命名函数:

function namedFun(err, data) {
  // ...
}
myclass.x(abc, namedFun);

Or even:甚至:

var namedFun = function (err, data) {
  // ...
}
myclass.x(abc, namedFun);

Functions in JavaScript are first-class objects like strings or arrays. JavaScript 中的函数是一流的对象,如字符串或数组。 You can pass a named function as a parameter to some other function:您可以将命名函数作为参数传递给其他函数:

function fun1(f) {
  return f(10);
}
function fun2(x) {
  return x*x;
}
fun1(fun2);

just like you can pass a named array:就像您可以传递命名数组一样:

function fun3(a) {
  return a[0]
}
var array = [1, 2, 3];
fun3(array);

And you can pass an anonymous function as a parameter:您可以将匿名函数作为参数传递:

function fun1(f) {
  return f(10);
}
fun1(function (x) {
  return x*x;
});

just like you can pass an anonymous array:就像您可以传递匿名数组一样:

function fun3(a) {
  return a[0]
}
fun3([1, 2, 3]);

There is also a nice shortcut so that instead of:还有一个很好的快捷方式,而不是:

fun1(function (x) {
  return x*x;
});

You can write:你可以写:

fun1(x => x*x);

Making my comment into an answer...将我的评论变成答案...

If the issue you're experiencing is that Z does not have the value you want when you are examining it, then that is probably because of a timing issue.如果您遇到的问题是Z在检查时没有您想要的值,那么这可能是因为时间问题。 Asynchronous callbacks happen at some unknown time in the future while the rest of your code continues to run.异步回调发生在未来某个未知时间,而其余代码继续运行。 Because of that, the only place you can reliably use the result passed to the asynchronous callback is inside the callback itself or in some function you would call from that function and pass it the value.因此,您可以可靠地使用传递给异步回调的结果的唯一地方是在回调本身内部或在您将从该函数调用并将值传递给它的某个函数中。

So, if your .x() method calls it's callback asynchronously, then:因此,如果您的.x()方法异步调用它的回调,则:

var Z;
myclass.x( function(err,data) {
    // use the err and data arguments here inside the callback
    Z = data;
});

console.log(Z);    // outputs undefined

// you can't access Z here.  Even when assigned 
// to higher scoped variables because the callback has not yet
// been called when this code executes

You can see this is a little more clearly by understanding the sequencing通过了解排序,您可以更清楚地看到这一点

console.log('A');
someAsyncFucntion(function() {
    console.log('B');
})
console.log('C');

This will produce a log of:这将产生以下日志:

A
C
B

Showing you that the async callback happens some time in the future, after the rest of your sequential code has executed.向您展示异步回调发生在未来某个时间,在您的其余顺序代码执行之后。


Java, on the other hand, primarily uses blocking I/O (the function doesn't return until the I/O operation is copmlete) so you don't usually have this asynchronous behavior that is standard practice in node.js.另一方面,Java 主要使用阻塞 I/O(该函数在 I/O 操作完成之前不会返回),因此您通常没有这种异步行为,这是 node.js 中的标准做法。 Note: I believe there are some asynchronous capabilities in Java, but that isn't the typical way things are done and in node.js, it is the typical ways things are done.注意:我相信 Java 中有一些异步功能,但这不是完成事情的典型方式,而在 node.js 中,这是完成事情的典型方式。

This creates a bit of an architectural mismatch if you're trying to port code that uses I/O from environment from another because the structure has to be redone in order to work properly in a node.js environment.如果您尝试从另一个环境移植使用 I/O 的代码,这会造成一些架构不匹配,因为必须重做结构才能在 node.js 环境中正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM