I am currently trying to understand Node and callbacks, and have tried various solutions to this code in order to get it to work, however param2 is coming back undefined. Can anybody tell me why? And how to fix this? Thanks!
我目前正在尝试理解Node和回调,并尝试了各种解决方案,以使其工作,但param2回来未定义。谁能告诉我为什么?以及如何解决这个问题?谢谢!
function getPage(callback) {
url = 'http://www.google.com';
if (url) {
url = url;
} else {
console.log('There was an error. No URL submitted');
}
callback(url, param2);
}
function CB(url, param2) {
console.log(`The URL of the page requested was ${url} and the added argument was ${param2}`);
}
getPage(CB);
2 个解决方案
#1
2
That's because param2
is undefined in the scope where you are calling the callback function. To have param2
come back defined, make sure param2
is initialized in getpage()
这是因为在调用回调函数的范围内未定义param2。要让param2返回定义,请确保在getpage()中初始化param2
function getPage(callback) {
url = 'http://www.google.com';
// **make sure param2 is defined**
var param2 = "param2 value"
if (url) {
url = url;
} else {
console.log('There was an error. No URL submitted');
}
callback(url, param2);
}
function CB(url, param2) {
console.log(`The URL of the page requested was ${url} and the added argument was ${param2}`);
}
getPage(CB);
#2
1
In getPage function, define param2 and pass it along
在getPage函数中,定义param2并传递它
#1
2
That's because param2
is undefined in the scope where you are calling the callback function. To have param2
come back defined, make sure param2
is initialized in getpage()
这是因为在调用回调函数的范围内未定义param2。要让param2返回定义,请确保在getpage()中初始化param2
function getPage(callback) {
url = 'http://www.google.com';
// **make sure param2 is defined**
var param2 = "param2 value"
if (url) {
url = url;
} else {
console.log('There was an error. No URL submitted');
}
callback(url, param2);
}
function CB(url, param2) {
console.log(`The URL of the page requested was ${url} and the added argument was ${param2}`);
}
getPage(CB);
#2
1
In getPage function, define param2 and pass it along
在getPage函数中,定义param2并传递它