综合开发

arguments to callback not being passed (Node.js)

微信扫一扫,分享到朋友圈

arguments to callback not being passed (Node.js)

In the code below, I am trying to pass the argument “test” to the callback. The good news is that the callback is indeed being called; however, the string “I see undefined” is being printed instead of “I see test”.

var MyObject = function(){
}
MyObject.prototype.b = function(data){
console.log("I see " + data);
}
a = function(callback){
callback("test");
}
var it = new MyObject();
a(function(){it.b()});

I have a hunch it has something to do with the closure, since I see the string “I see test” printed if I call it.b(“test”) directly. Why isn’t the function receiving the argument properly?

Problem courtesy of: Michael D. Moffitt

Solution

You are calling it.b()
with no arguments, so it should be no surprise that there are no arguments when you get in the b()
method. If you want an argument to appear for it.b()
, you have to declare it in your callback so you can then pass it to it.b(arg)
.

a(function(arg){
it.b(arg)
});

Or, you could pass all arguments from the callback:

a(function(){
it.b.apply(it, arguments)
});

Or, you could use .bind()
.

a(it.b.bind(it));

Solution courtesy of: jfriend00

Discussion

Lets analyse the last line of your code:

a(function(){it.b()});
//I will name the above function 'xyz' for convenience
a(function xyz(){it.b()});

In the above line you are passing a function xyz as an arguement to a(). The function you are passing directly calls it.b() without passing it any paramter.

So what happens here is that when you pass xyz to a(), xyz is called with string “test” as a parameter i.e xyz(“test”) is called. But this string “test” is not of any use as you are directly calling it.b() without passing it any data and hence you get ‘undefined’.

To get the output you desire you need to write the code by any of the following two methods.

Method 1:

var MyObject = function(){
}
MyObject.prototype.b = function(data){
console.log("I see " + data);
}
a = function(callback){
callback("test");
}
var it = new MyObject();
a(it.b);

Method 2:

var MyObject = function(){
}
MyObject.prototype.b = function(data){
console.log("I see " + data);
}
a = function(callback){
callback("test");
}
var it = new MyObject();
a(function(data){it.b(data)});

Discussion courtesy of: shinobi

It appears that you are creating a new anonymous function that you are passing as the callback to a. If you change that last line to:

a(it.b);

Everything should work as you’re expecting.

Discussion courtesy of: David

This recipe can be found in it’s original form on Stack Over Flow
.

微信扫一扫,分享到朋友圈

arguments to callback not being passed (Node.js)

Ability to generate sequential numbers without a database table?

上一篇

Kubernetes 二进制添加Node节点

下一篇

你也可能喜欢

评论已经被关闭。

插入图片

热门栏目

arguments to callback not being passed (Node.js)

长按储存图像,分享给朋友